﻿using AGVController.BaseClass;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UYD_WCS_AS_AGV_Controller.AGV.Fork;
using UYD_WCS_AS_AGV_Controller.BaseClass;
using WebSocket4Net;
using Newtonsoft.Json;
using UYD_WCS.DBUtility;

namespace UYD_WCS_AS_AGV_Controller
{
    public partial class FrmMain : Form
    {

        // AGV实时任务状态 0：空闲 /1：待执行/2：取货行走中/3：取货货叉移动完成/4:到达取货位/5：取货完成/
        // 6：放货行走中/7：放货货叉移动完成/8：到达放货位/9：放货完成/10：放货返回移动中/11：任务完成(到达默认位置)
        // 100:任务取消

        #region 系统定义变量
        UYD_WCS.Common.INIFile iniFile = new UYD_WCS.Common.INIFile(Application.ExecutablePath + "../../SYS.ini");
        CTaskStatusValue cTaskStatus = new CTaskStatusValue();
        #endregion

        #region 串口程序控制
        private int allThreadValue = 0;
        #region 货叉PLC线程

        private int InitSRM1ComFlag = 0;
        public static PLCOperate_AgvFork plcSRM1 = new PLCOperate_AgvFork();
        private Thread PLCSRM1ReadThread = null;
        private Thread PLCSRM1WriteThread = null;
        #endregion

        #region 系统整体控制线程

        private Thread AgvForkControlThread = null;
        #endregion

        #endregion


        #region 仙工AGV全局回调函数

        private readonly AGV.AgvStatusManager _agvStatusManager = new AGV.AgvStatusManager();
        public AGVController.AgvModel.robot_config_push_res currentAgvStatus = new AGVController.AgvModel.robot_config_push_res();
        #endregion


        public FrmMain()
        {
            InitializeComponent();
            this.DoubleBuffered = true;//设置本窗体
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲


            #region 仙工AGV定义

            // 注册全局回调
            _agvStatusManager.RegisterGlobalCallback(HandleAgvStatusChange);

            //所推送的数据传到当前页面中来
            if (BasicInfo.AgvService != null)
                BasicInfo.AgvService.AgvPushApi.GetAgvStatus += AgvStatusReceiver;

            // 绑定UI控件
            BindControlToVariable(lbtarget_id, "target_id");
            BindControlToVariable(lbcurrent_station, "current_station");
            BindControlToVariable(lbblocked, "blocked");
            BindControlToVariable(lbbattery_level, "battery_level");
            BindControlToVariable(lbcharging, "charging");
            BindControlToVariable(lbemergency, "emergency");
            BindControlToVariable(lbfatals, "fatals");
            BindControlToVariable(lberrors, "errors");
            BindControlToVariable(lbwarnings, "warnings");
            BindControlToVariable(lbsoft_emc, "soft_emc");
            BindControlToVariable(lbreloc_status, "reloc_status");
            BindControlToVariable(lbtask_status, "task_status");
            BindControlToVariable(lbtask_type, "task_type");
            #endregion

        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }

        #region 仙工AGV状态变化回调函数

        // 统一变化处理
        private void HandleAgvStatusChange(string varName, object oldVal, object newVal)
        {
            //if (InvokeRequired)
            //{
            //    BeginInvoke(new Action(() => HandleAgvStatusChange(varName, oldVal, newVal)));
            //    return;
            //}
            // 示例逻辑
            switch (varName)
            {
                case "current_station":
                    //存储当前站点
                    iniFile.IniWriteValue("SysInfo", "AGV_CurrentLocNo", newVal.ToString());

                    break;
                case "task_status":
                    //任务状态变化了，=4表示完成，整体任务状态变化
                    if(CTaskInfo.CurrentTask!=null)
                    {
                        if (currentAgvStatus.task_status == 4)
                        {
                            AddListBak("QB001AGV到达货位:" + CTaskInfo.CurrentTask.endPosition + ":" + CTaskInfo.CurrentTask.endAgvLoc+ "CTaskInfo.CurrentTask.taskStatus=" + CTaskInfo.CurrentTask.taskStatus);
                            if (CTaskInfo.CurrentTask.startAgvLoc == currentAgvStatus.current_station &&(CTaskInfo.CurrentTask.taskStatus == 2 || CTaskInfo.CurrentTask.taskStatus == 3|| CTaskInfo.CurrentTask.taskStatus == -4))
                            {  if (CTaskInfo.CurrentTask.taskStatus == 2)//先货叉移动完成，状态变为货叉取货状态
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 3);//货叉没有移动完成，状态变为货叉移动状态
                                    CTaskInfo.CurrentTask.taskStatus = 3;
                                    AddListBak("AGV到达取货位:" + CTaskInfo.CurrentTask.startPosition + ":" + CTaskInfo.CurrentTask.startAgvLoc);
                                    AddListBak("取货货叉没有移动完成，状态变为:3");
                                }
                                else
                                if (CTaskInfo.CurrentTask.taskStatus == -4)//先货叉移动完成，状态变为货叉取货状态
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 4);
                                    CTaskInfo.CurrentTask.taskStatus = 4;
                                    AddListBak("AGV到达取货位:" + CTaskInfo.CurrentTask.startPosition + ":" + CTaskInfo.CurrentTask.startAgvLoc);
                                    AddListBak("取货前货叉移动完成，状态变为:4" );
                                }
                                else if (CTaskInfo.CurrentTask.taskStatus == 3)//先货叉移动完成，状态变为货叉取货状态
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 4);//货叉没有移动完成，状态变为货叉移动状态
                                    CTaskInfo.CurrentTask.taskStatus = 4;
                                    AddListBak("AGV到达取货位:" + CTaskInfo.CurrentTask.startPosition + ":" + CTaskInfo.CurrentTask.startAgvLoc);
                                    AddListBak("取货货叉没有移动完成，状态变为:4");
                                }
                            }
                            else if (CTaskInfo.CurrentTask.endAgvLoc == currentAgvStatus.current_station && (CTaskInfo.CurrentTask.taskStatus == 6|| CTaskInfo.CurrentTask.taskStatus == -8))
                            {
                                if (CTaskInfo.CurrentTask.taskStatus == -8)//先货叉移动完成，状态变为货叉放货状态
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 8);
                                    CTaskInfo.CurrentTask.taskStatus = 8;
                                    AddListBak("AGV到达放货位:" + CTaskInfo.CurrentTask.endPosition + ":" + CTaskInfo.CurrentTask.endAgvLoc);
                                    AddListBak("放货先货叉移动完成，状态变为:8");
                                }
                                else if (CTaskInfo.CurrentTask.taskStatus == 6)//先货叉移动完成，状态变为货叉放货状态
                                {
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 7);//货叉没有移动完成，状态变为货叉移动状态
                                    CTaskInfo.CurrentTask.taskStatus = 7;
                                    AddListBak("AGV到达放货位:" + CTaskInfo.CurrentTask.endPosition + ":" + CTaskInfo.CurrentTask.endAgvLoc);
                                    AddListBak("放货先货叉移动完成，状态变为:7");
                                }
                                

                              }
                            else if (CTaskInfo.AgvGetSetPointLoc == currentAgvStatus.current_station && CTaskInfo.CurrentTask.taskStatus == 10)
                            {
                                UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 11);
                                CTaskInfo.CurrentTask.taskStatus = 11;
                                AddListBak("AGV到达初始货位(取放货口):" + CTaskInfo.AgvGetSetPointLoc+ ",任务" + CTaskInfo.CurrentTask.taskCode + "执行完成");

                                CTaskInfo.CurrentTask = null;
                                CTaskInfo.PLCSRMTaskSendList.Clear();
                                CTaskInfo.AGVTaskSendList.Clear();
                                FlushPage();
                            }
                        }
                    }
                   
                    AddListBak("task_status="+newVal.ToString()+ "currentAgvStatus.task_status="+ currentAgvStatus.task_status );
                    break;
                case "battery_level":
                    //电量不足，判断当前是否有任务，没有任务去充电

                    double dbattery_level = ((double)newVal) * 100;
                    if (dbattery_level < int.Parse(CTaskInfo.AgvAutoChangeLowValue))
                    {
                        //开启自动充电
                        if (CTaskInfo.CurrentTask == null && !currentAgvStatus.charging)
                        {
                            if (CTaskInfo.AgvGetSetPointLoc == currentAgvStatus.current_station)
                            {
                                cTaskStatus.AgvAutoChange = 0;
                                cTaskStatus.AgvAutoChange = 1;
                                AddListBak("电量不足开始自动充电");
                            }
                        }
                        else
                        {
                            //AddListBak("自动充电时有任务");
                        }
                    }
                    else if(dbattery_level>90&&currentAgvStatus.current_station==CTaskInfo.AgvChargingLoc&&!currentAgvStatus.charging)
                    {
                        AddListBak("自动充电完成,回到起始位");

                        //string strGetSetPointLoc_Agv = getAgvLoc(CTaskInfo.AgvGetSetPointLoc);
                        string strGetSetPointLoc_Agv = CTaskInfo.AgvGetSetPointLoc;
                        if (!string.IsNullOrEmpty(strGetSetPointLoc_Agv))
                        {
                            AGVController.AgvModel.robot_base_res rbs = new AGVController.AgvModel.robot_base_res();
                            rbs = BasicInfo.AgvService.addTask(CTaskInfo.AgvChargingLoc, strGetSetPointLoc_Agv);
                            if (rbs.ret_code == 0)
                            {
                                AddListBak("AGV任务下发:(" + CTaskInfo.AgvChargingLoc + ")-(" + strGetSetPointLoc_Agv + ")成功");
                            }
                            else
                            {
                                AddListBak("AGV任务下发失败," + CTaskInfo.AgvChargingLoc + "-" + strGetSetPointLoc_Agv + ", 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                            }
                        }
                        else
                            AddListBak("默认初始化位置设置错误,未获取到AGV对应储位");
                    }
                    break;
            }
        }


        // 通用数据绑定方法
        private void BindControlToVariable(Control control, string statusName)
        {
            var variable = _agvStatusManager.GetObservableAgvStatus(statusName);
            if (variable == null) return;

            // 变量→控件绑定
            variable.PropertyChanged += (sender, e) =>
            {
                if (control.InvokeRequired)
                {
                    control.BeginInvoke(new EventHandler(delegate
                    {
                    switch (statusName)
                    {
                        case "current_station":
                        case "target_id":
                            if (variable.Value.ToString() == "")
                            {
                                control.BackColor = Color.LightSteelBlue;
                                control.Text = "";
                            }
                            else
                            {
                                control.BackColor = Color.Green;
                                control.Text = variable.Value.ToString();
                            }
                            break;
                        case "task_type":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                control.Text = EnumHelper.Get_task_type_Description((double)variable.Value);
                                control.BackColor = Color.Green;
                            }
                            break;
                        case "task_status":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                control.Text = EnumHelper.Get_task_status_Description((double)variable.Value);
                                control.BackColor = Color.Green;
                            }
                            break;
                        case "reloc_status":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                control.Text = EnumHelper.Get_reloc_status_Description((double)variable.Value);
                                control.BackColor = Color.Green;
                            }
                            break;
                        case "battery_level":
                                if (variable.Value.ToString() == "")
                                {
                                    control.Text = "0";
                                    control.BackColor = Color.LightSteelBlue;
                                }
                                else
                                {
                                    double dbattery_level = ((double)variable.Value) * 100;
                                    control.Text = dbattery_level.ToString();

                                    if (dbattery_level > 35)
                                    {
                                        control.BackColor = Color.Lime;
                                    }
                                    else
                                    {
                                        control.BackColor = Color.Red;
                                    }
                                }
                                break;
                            case "blocked":
                            case "charging":
                            case "emergency":
                            case "soft_emc":
                                bool bl = (bool)variable.Value;
                                if (bl)
                                {
                                    control.BackColor = Color.Green;
                                }
                                else
                                {
                                    control.BackColor = Color.LightSteelBlue;
                                }
                                break;
                            case "fatals":
                            case "errors":
                            case "warnings":
                                try
                                {
                                    List<AGVController.AgvModel.AGVWarnings> listErrorTmp = (List<AGVController.AgvModel.AGVWarnings>)variable.Value;
                                    foreach (AGVController.AgvModel.AGVWarnings warnings  in listErrorTmp)
                                    {
                                        AddListBak_Agv("AGV异常-(" + warnings.desc + ")");
                                    }
                                  // List<AGV.Model.AGVWarnings> listErrorTmp = JsonConvert.DeserializeObject<List<AGV.Model.AGVWarnings>>(variable.Value.ToString());
                                    if (listErrorTmp.Count > 0)
                                    {
                                        string AGVWarningsString = "";
                                        foreach (AGVController.AgvModel.AGVWarnings warnings in listErrorTmp)
                                        {
                                            AGVWarningsString += warnings.desc;
                                        }
                                        control.Text = AGVWarningsString;
                                        control.BackColor = Color.Red;
                                        //Thread thread = new Thread(new ParameterizedThreadStart(SendAgvTaskStatusGetFinish));

                                        //thread.Start(AGVWarningsString);

                                    }
                                    else
                                    {
                                        control.Text = "";
                                        control.BackColor = Color.LightSteelBlue;
                                    }


                                    //List<string> listError = new List<string>();
                                    //foreach (object obj in listErrorTmp)
                                    //{
                                    //    listError.Add(obj.ToString());
                                    //}
                                    //if (listError.Count > 0)
                                    //{
                                    //    control.Text = string.Join("#", listError.ToArray());
                                    //    control.BackColor = Color.Red;
                                    //}
                                    //else
                                    //{
                                    //    control.Text = "";
                                    //    control.BackColor = Color.LightSteelBlue;
                                    //}
                                }
                                catch(Exception ex) {
                                    AddListBak_Agv("AGV异常-(" + ex.Message + ")");

                                }
                                break;
                        }
                    }));
                }
                else
                {
                    switch (statusName)
                    {
                        case "current_station":
                        case "target_id":
                            if (variable.Value.ToString() == "")
                            {
                                control.BackColor = Color.LightSteelBlue;
                                control.Text = "";
                            }
                            else
                            {
                                control.BackColor = Color.Green;
                                control.Text = variable.Value.ToString();
                            }
                            break;
                        case "task_type":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                control.Text = EnumHelper.Get_task_type_Description((double)variable.Value);
                                control.BackColor = Color.Green;
                            }
                            break;
                        case "task_status":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                control.Text = EnumHelper.Get_task_status_Description((double)variable.Value);
                                control.BackColor = Color.Green;
                            }
                            break;
                        case "reloc_status":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                control.Text = EnumHelper.Get_reloc_status_Description((double)variable.Value);
                                control.BackColor = Color.Green;
                            }
                            break;
                        case "battery_level":
                            if (variable.Value.ToString() == "")
                            {
                                control.Text = "0";
                                control.BackColor = Color.LightSteelBlue;
                            }
                            else
                            {
                                double dbattery_level = ((double)variable.Value) * 100;
                                control.Text = dbattery_level.ToString();

                                if (dbattery_level > 35)
                                {
                                    control.BackColor = Color.Lime;
                                }
                                else
                                {
                                    control.BackColor = Color.Red;
                                }
                            }
                            break;
                        case "blocked":
                        case "charging":
                        case "emergency":
                        case "soft_emc":
                            bool bl = (bool)variable.Value;
                            if (bl)
                            {
                                control.BackColor = Color.Green;
                            }
                            else
                            {
                                control.BackColor = Color.LightSteelBlue;
                            }
                            break;
                        case "fatals":
                        case "errors":
                        case "warnings":
                            try
                            {
                                List<AGVController.AgvModel.AGVWarnings> listErrorTmp = (List<AGVController.AgvModel.AGVWarnings>)variable.Value;
                                foreach (AGVController.AgvModel.AGVWarnings warnings in listErrorTmp)
                                {
                                    AddListBak_Agv("AGV异常-(" + warnings.desc + ")");
                                }

                                //List<AGV.Model.AGVWarnings> listErrorTmp = JsonConvert.DeserializeObject < List < AGV.Model.AGVWarnings >>( variable.Value.ToString());
                                if (listErrorTmp.Count > 0)
                                {
                                    string AGVWarningsString = "";
                                    foreach (AGVController.AgvModel.AGVWarnings warnings in listErrorTmp)
                                    {
                                        AGVWarningsString += warnings.desc;
                                    }
                                    control.Text = AGVWarningsString;
                                    control.BackColor = Color.Red;
                                    //Thread thread = new Thread(new ParameterizedThreadStart(SendAgvTaskStatusGetFinish));

                                    //thread.Start(AGVWarningsString);

                                }
                                else
                                {
                                    control.Text = "";
                                    control.BackColor = Color.LightSteelBlue;
                                }


                                //List<string> listError = new List<string>();
                                //foreach (object obj in listErrorTmp)
                                //{
                                //    listError.Add(obj.ToString());
                                //}
                                //if (listError.Count > 0)
                                //{
                                //    control.Text = string.Join("#", listError.ToArray());
                                //    control.BackColor = Color.Red;
                                //}
                                //else
                                //{
                                //    control.Text = "";
                                //    control.BackColor = Color.LightSteelBlue;
                                //}
                            }
                            catch (Exception ex)
                            {
                                AddListBak_Agv("AGV异常-(" + ex.Message + ")");

                            }
                            //List<object> listErrorTmp = (List<object>)variable.Value;

                            //List<string> listError = new List<string>();
                            //foreach (object obj in listErrorTmp)
                            //{
                            //    listError.Add(obj.ToString());
                            //}
                            //if (listError.Count > 0)
                            //{
                            //    control.Text = string.Join("#", listError.ToArray());
                            //    control.BackColor = Color.Red;
                            //}
                            //else
                            //{
                            //    control.Text = "";
                            //    control.BackColor = Color.LightSteelBlue;
                            //}
                            break;
                    }
                }
            };

        }
       
        private void SendAgvTaskStatusGetFinish(object obj)
        {
            try
            {

                string AlarmInfo = obj.ToString();
                 #region 给WCS发送报警

                  WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);

                  sendToWcs.SendAgvWarn(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), AlarmInfo, CTaskInfo.CurrentTask.taskCode);
                #endregion
               
            }
            catch (Exception exc)
            {

            }
        }
        private void AgvStatusReceiver(AGVController.AgvModel.robot_config_push_res rp)
        {
            //赋值总任务状态信息，任务状态和当前站点和电池电量
            currentAgvStatus = rp;

            _agvStatusManager.GetObservableAgvStatus("task_type").Value = rp.task_type;
            _agvStatusManager.GetObservableAgvStatus("task_status").Value = rp.task_status;
            _agvStatusManager.GetObservableAgvStatus("blocked").Value = rp.blocked;
            _agvStatusManager.GetObservableAgvStatus("battery_level").Value = rp.battery_level;
            _agvStatusManager.GetObservableAgvStatus("charging").Value = rp.charging;
            _agvStatusManager.GetObservableAgvStatus("emergency").Value = rp.emergency;
            _agvStatusManager.GetObservableAgvStatus("soft_emc").Value = rp.soft_emc;
            _agvStatusManager.GetObservableAgvStatus("reloc_status").Value = rp.reloc_status;
            _agvStatusManager.GetObservableAgvStatus("current_station").Value = rp.current_station;
            _agvStatusManager.GetObservableAgvStatus("target_id").Value = rp.target_id;

            _agvStatusManager.GetObservableAgvStatus("fatals").Value = rp.fatals;
            _agvStatusManager.GetObservableAgvStatus("errors").Value = rp.errors;
            _agvStatusManager.GetObservableAgvStatus("warnings").Value = rp.warnings;


        }


        private string getAgvLoc(string wcsLoc)
        {
            string startAgvLoc = ""; 
            string sql = " SELECT * FROM WCS_AGV_LOC WHERE WCS_LOC='" + wcsLoc + "';  ";
            DataSet dsAgvLoc = DbHelperSQLite.Query(sql);
            if (dsAgvLoc != null)
                if (dsAgvLoc.Tables.Count > 0)
                    if (dsAgvLoc.Tables[0].Rows.Count > 0)
                    {
                        startAgvLoc = dsAgvLoc.Tables[0].Rows[0]["startAgvLoc"].ToString(); 
                    }
            return startAgvLoc;
        }
        #endregion

        private void FrmMain_Load(object sender, EventArgs e)
        {
            InitGlobalVariable();

            #region 初始化wcs连接串口
            InitCom();
            #endregion

            cTaskStatus.AgvAutoChangeEvent += CTaskStatus_AgvAutoChangeEvent;

            cTaskStatus.SRM_GetGoodsApplyEnent += CTaskStatus_SRM_GetGoodsApplyEnent;

            cTaskStatus.SRM_SetGoodsApplyEnent += CTaskStatus_SRM_SetGoodsApplyEnent;

            #region 货叉
            cTaskStatus.SRM_Get_Finish_Event += CTaskStatus_SRM_Get_Finish_Event;

            cTaskStatus.SRM_Set_Finish_Event += CTaskStatus_SRM_Set_Finish_Event;

            cTaskStatus.SRM_Task_Finish_Event += CTaskStatus_SRM_Task_Finish_Event;
            
            cTaskStatus.SRMBreakDownEvent += CTaskStatus_SRMBreakDownEvent;
            
            #endregion

            #region AGV急停或者复位
            cTaskStatus.AGV_Estop_Event += CTaskStatus_AGV_Estop_Event;

            cTaskStatus.AGV_Reset_Event += CTaskStatus_AGV_Reset_Event;
            #endregion


            InitComThread();

            timer2.Enabled = true;
        }

        private void CTaskStatus_AGV_Reset_Event(object sender, EventArgs e)
        {
            try
            {
                AddListBak("接收到急停报警复位");
                AgvPauseOrReset(false);
            }
            catch
            {

            }
        }

        private void CTaskStatus_AGV_Estop_Event(object sender, EventArgs e)
        {
            try
            {
                AddListBak("接收到急停报警");
                AgvPauseOrReset(true);
            }
            catch
            {

            }
        }

        private void CTaskStatus_AgvAutoChangeEvent(object sender, EventArgs e)
        {
            try
            {
                AGVController.AgvModel.robot_base_res rbs = new AGVController.AgvModel.robot_base_res();
                rbs = BasicInfo.AgvService.addTask("SELF_POSITION", CTaskInfo.AgvChargingLoc);
                if (rbs.ret_code == 0)
                {
                    AddListBak_Agv("AGV自动充电任务下发:(SELF_POSITION)-(" + CTaskInfo.AgvChargingLoc + ")成功");
                }
                else
                {
                    AddListBak("AGV自动充电任务下发错误,SELF_POSITION-" + CTaskInfo.AgvChargingLoc + ", 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                }
            }
            catch (Exception exc)
            {
                AddListBak("AGV自动充电任务下发异常" + exc.Message);

            }
        }

        private void CTaskStatus_SRM_Task_Finish_Event(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_Task_Finished_ToWcs_Addr, 1, 0, 1, 1);
            if (CTaskInfo.CurrentTask != null)
            {
                if (CTaskInfo.CurrentTask.taskStatus == 2)//AGV行走中货叉移动完成状态变24
                {
                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, -4);
                    CTaskInfo.CurrentTask.taskStatus = -4;
                    CTaskInfo.CurrentTask.forkHStatus = "2";
                }
                else
                if (CTaskInfo.CurrentTask.taskStatus == 3)//AGV行走结束货叉移动也结束变4执行取货
                {
                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 4);
                    CTaskInfo.CurrentTask.taskStatus = 4;
                    CTaskInfo.CurrentTask.forkHStatus = "2";
                }
                else
                if (CTaskInfo.CurrentTask.taskStatus == 5)
                {
                    CTaskInfo.CurrentTask.forkHStatus = "2";
                }
                else if (CTaskInfo.CurrentTask.taskStatus == 6)//AGV行走中货叉移动完成状态变-8
                {
                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, -8);
                    CTaskInfo.CurrentTask.taskStatus = -8;
                }
                else if (CTaskInfo.CurrentTask.taskStatus == 7)//AGV行走结束货叉移动也结束变4执行放货
                {
                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 8);
                    CTaskInfo.CurrentTask.taskStatus = 8;
                }
                AddListBak("接收到货叉移动完成信号，任务状态为" + CTaskInfo.CurrentTask.taskStatus);

            }
            else
            {
                AddListBak("接收到货叉移动完成信号，任务状态为空");
            }
        }

        private void CTaskStatus_SRM_Set_Finish_Event(object sender, EventArgs e)
        {
            try
            {
                AddListBak("接收到货叉放货完成信号");
                if (CTaskInfo.CurrentTask != null)
                {
                    if (CTaskInfo.CurrentTask.taskStatus == 8)
                    {
                        UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 9);
                        CTaskInfo.CurrentTask.taskStatus = 9;

                        Thread thread = new Thread(new ThreadStart(SendAgvTaskStatusSetFinish));

                        thread.Start();
                        
                    }
                }
                AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
            }
            catch (Exception exc)
            {
                AddListBak("放货完成后,数据处理异常" + exc.Message + exc.StackTrace);
            }
        }

        private void CTaskStatus_SRM_Get_Finish_Event(object sender, EventArgs e)
        {
            try
            {
                AddListBak("接收到货叉取货完成信号");
                if (CTaskInfo.CurrentTask != null)
                {
                    if (CTaskInfo.CurrentTask.startAgvLoc == currentAgvStatus.current_station)
                    {
                        if (CTaskInfo.CurrentTask.taskStatus < 5)
                        {
                            UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 5);
                            CTaskInfo.CurrentTask.taskStatus = 5;

                            AddListBak("开始给输送线下发取货完成");
                            Thread thread = new Thread(new ThreadStart(SendAgvTaskStatusGetFinish));

                            thread.Start();

                            AddListBak("开始给输送线下发取货完成继续");
                            #region 给WCS发送取货完成
                            //WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                            //sendToWcs.SendAgvTaskStatus(CTaskInfo.CurrentTask.startPosition, "outbin", CTaskInfo.CurrentTask.taskCode);
                            #endregion
                        }
                    }
                }

                AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
            }
            catch (Exception exc)
            {
                AddListBak("取货完成后,数据处理异常" + exc.Message + exc.StackTrace);
            }
        }

        private void CTaskStatus_SRM_GetGoodsApplyEnent(object sender, EventArgs e)
        {
            try
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_GetGoodsAllow_ToPlc_Addr, 1, 1, 1, 1);
                AddListBak(" 给货叉PLC DB540.44.0 下发取货允许=1指令");
            }
            catch (Exception exc)
            {
                AddListBak("给输送线下发取货允许时异常");
            }

        }
       
        private void CTaskStatus_SRM_SetGoodsApplyEnent(object sender, EventArgs e)
        {
            try
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_SetGoodsAllow_ToPlc_Addr, 1, 1, 1, 1);
                AddListBak(" 给货叉PLC DB540.46.0 下发放货允许=1指令");
            }
            catch (Exception exc)
            {
                AddListBak("给输送线下发放货允许时异常");
            }
        }

        private void CTaskStatus_SRMBreakDownEvent(object sender, EventArgs e)
        {
            try
            {
                string AlarmInfo = GetForkAlarmTxt(cTaskStatus.SRM_BreakDownInfo);
                #region 给WCS发送报警

                //WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);

                //sendToWcs.SendAgvWarn(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), AlarmInfo, CTaskInfo.CurrentTask.taskCode);
                #endregion
            }
            catch (Exception exc)
            {
               
            }
        }

        private void SendAgvTaskStatusGetFinish()
        {
            try
            {
                //Thread.Sleep(3 * 1000);
                Thread.Sleep(100);
                //如果有报警
                if (cTaskStatus.SRM_Alarm == 1)
                {
                    string AlarmInfo = GetForkAlarmTxt(cTaskStatus.SRM_BreakDownInfo);
                    #region 给WCS发送报警

                    WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);

                    sendToWcs.SendAgvWarn(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), AlarmInfo, CTaskInfo.CurrentTask.taskCode);
                    #endregion
                }
                else
                {
                    #region 给WCS发送放货完成
                    WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                    sendToWcs.SendAgvTaskStatus(CTaskInfo.CurrentTask.endPosition, "outbin", CTaskInfo.CurrentTask.taskCode);
                    #endregion

                }
            }
            catch (Exception exc)
            {
               
            }
        }

        private void SendAgvTaskStatusSetFinish()
        {
            try
            {
                //Thread.Sleep(3 * 1000);
                Thread.Sleep(100);
                //如果有报警
                if (cTaskStatus.SRM_Alarm == 1)
                {
                   string AlarmInfo = GetForkAlarmTxt(cTaskStatus.SRM_BreakDownInfo);
                    #region 给WCS发送报警

                    WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                    sendToWcs.SendAgvWarn(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), AlarmInfo, CTaskInfo.CurrentTask.taskCode);
                    #endregion
                }
                else
                {
                    #region 给WCS发送放货完成
                    WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                    sendToWcs.SendAgvTaskStatus(CTaskInfo.CurrentTask.endPosition, "end", CTaskInfo.CurrentTask.taskCode);
                    #endregion

                }
            }
            catch (Exception exc)
            {

            }
        }
      
        public void InitComThread()
        {
            try
            {
                if (InitSRM1ComFlag > 0)
                {
                    PLCSRM1ReadThread = new Thread(new ThreadStart(UnitPLCSRM_Read));
                    PLCSRM1ReadThread.Start();
                    PLCSRM1WriteThread = new Thread(new ThreadStart(UnitPLCSRM_Write));
                    PLCSRM1WriteThread.Start();
                }

                AgvForkControlThread = new Thread(new ThreadStart(AgvForkControlStart));
                AgvForkControlThread.Start();

            }
            catch (Exception s)
            {
                AddListBak("初始化串口线程异常" + s.Message);
            }
        }

        #region 系统整体控制线程

        /// <summary>
        /// AGV 货叉整体控制线程
        /// </summary>
        private void AgvForkControlStart()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;

                try
                {
                    //---------------------------------start----------------------------------//

                    // AddListBak(DateTime.Now.ToString()+"AGV急停被触发!");
                    string strWhere = " taskStatus<=11 AND taskStatus>-10 ";
                    CTaskInfo.CurrentTask = GetAgvTaskModel(strWhere);
                    if (CTaskInfo.CurrentTask != null)
                    {
                        FlushPage(1);
                        // continue;
                        #region 设备状态判断

                        if (BasicInfo.AgvService == null)
                        {
                            AddListBak("AGV端口通信失败!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        if (!BasicInfo.AgvService.AgvConneed)
                        {
                            AddListBak("AGV未连接!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        if (currentAgvStatus.emergency)
                        {
                            AddListBak("AGV急停被触发!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        else if (currentAgvStatus.soft_emc)
                        {
                            AddListBak("AGV软急停被触发!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        //else if (currentAgvStatus.charging)
                        //{
                        //    AddListBak("AGV正在充电请等待!");
                        //    Thread.Sleep(10000);
                        //    continue;
                        //}
                        else if (currentAgvStatus.fatals != null && currentAgvStatus.fatals.Count > 0)
                        {
                            AddListBak("AGV有致命性报警,请检查!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        else if (currentAgvStatus.errors != null && currentAgvStatus.errors.Count > 0)
                        {
                            AddListBak("AGV有错误性报警,请检查!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        else if (currentAgvStatus.warnings != null && currentAgvStatus.warnings.Count > 0)
                        {
                            AddListBak("AGV有警告类报警,请检查!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        else if (cTaskStatus.SRM_Alarm == 1)
                        {
                            AddListBak("货叉有报警,请检查!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        else if (cTaskStatus.SRM_ForkInZero == 0)
                        {
                            AddListBak("货叉不在原点,请检查!");
                            Thread.Sleep(10000);
                            continue;
                        }
                        else if (cTaskStatus.SRM_RemoteAuto == 0)
                        {
                            AddListBak("货叉远程自动模式未启动!");
                            Thread.Sleep(10000);
                            continue;
                        }

                        #endregion


                        if (CTaskInfo.CurrentTask.taskStatus == 1)
                        {
                            CTaskInfo.PLCSRMTaskSendList.Clear();
                            CTaskInfo.AGVTaskSendList.Clear();

                            if (currentAgvStatus.current_station != CTaskInfo.CurrentTask.startAgvLoc)
                            {
                                if (!CTaskInfo.AGVTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                                 && x.startAgvLoc == "SELF_POSITION"
                                 && x.endAgvLoc == CTaskInfo.CurrentTask.endAgvLoc))
                                {
                                    AGVController.AgvModel.robot_base_res rbs = BasicInfo.AgvService.addTask("SELF_POSITION", CTaskInfo.CurrentTask.startAgvLoc);
                                    if (rbs.ret_code == 0)
                                    {
                                        AddListBak("AGV任务下发:(" + currentAgvStatus.current_station + ")-" + CTaskInfo.CurrentTask.startPosition + "(" + CTaskInfo.CurrentTask.startAgvLoc + ")");
                                        UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 2);
                                        CTaskInfo.CurrentTask.taskStatus = 2;

                                        CTaskInfo.AGVTaskSendList.Add(new AGVTaskSend
                                        {
                                            taskCode = CTaskInfo.CurrentTask.taskCode,
                                            startAgvLoc = "SELF_POSITION",
                                            endAgvLoc = CTaskInfo.CurrentTask.startAgvLoc
                                        });
                                        //当前位置不在取货点，行走的同时升降货叉，此时货叉是空的
                                        //货叉移动指令下以
                                        Thread.Sleep(6000);
                                        short shRow = CTaskInfo.CurrentTask.startLocGroup;
                                        short shCell = CTaskInfo.CurrentTask.startLocColl;
                                        short shFloor = CTaskInfo.CurrentTask.startLocFloor;
                                        if (cTaskStatus.SRM_Task_Finish != 0)
                                        {
                                            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
                                        }
                                        AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);// 取消货叉任务
                                                                                                               //复位
                                        AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
                                        Thread.Sleep(500);
                                        AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);



                                        AGVForkSendCode(shRow, shCell, shFloor, 1);

                                        AddListBak("AGV任务下发移动命令后货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.startPosition);
                                    }
                                    else
                                    {
                                        AddListBak("AGV任务下发失败," + currentAgvStatus.current_station + "-" + CTaskInfo.CurrentTask.startAgvLoc + ", 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                                        Thread.Sleep(1000 * 5);
                                    }
                                }
                            }
                            else
                            {
                                UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 3);
                                CTaskInfo.CurrentTask.taskStatus = 3;
                                AddListBak("AGV在货位:" + CTaskInfo.CurrentTask.startPosition);
                                #region AGV在原位货叉移动任务下发完成,移动货位
                                /*
                                if (!CTaskInfo.PLCSRMTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                                 && x.taskType == 1
                                 && x.taskGroup == CTaskInfo.CurrentTask.startLocGroup
                                 && x.taskColl == CTaskInfo.CurrentTask.startLocColl
                                 && x.taskFloor == CTaskInfo.CurrentTask.startLocFloor))
                                {
                                    short shRow = CTaskInfo.CurrentTask.startLocGroup;
                                    short shCell = CTaskInfo.CurrentTask.startLocColl;
                                    short shFloor = CTaskInfo.CurrentTask.startLocFloor;
                                   
                                    
                                    AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);// 取消货叉任务
                                                                                                           //复位
                                    AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
                                    Thread.Sleep(500);
                                    AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);


                                    AGVForkSendCode(shRow, shCell, shFloor, 1);
                                    AddListBak("AGV在原位货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.startPosition);
                                }
                                */
                                #endregion
                            }
                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 3)
                        {
                            if (!CTaskInfo.PLCSRMTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                             && x.taskType == 1
                             && x.taskGroup == CTaskInfo.CurrentTask.startLocGroup
                             && x.taskColl == CTaskInfo.CurrentTask.startLocColl
                             && x.taskFloor == CTaskInfo.CurrentTask.startLocFloor))
                            {
                                short shRow = CTaskInfo.CurrentTask.startLocGroup;
                                short shCell = CTaskInfo.CurrentTask.startLocColl;
                                short shFloor = CTaskInfo.CurrentTask.startLocFloor;

                                if (cTaskStatus.SRM_Task_Finish != 0)
                                {
                                    AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);

                                }
                                AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);// 取消货叉任务
                                                                                                       //复位
                                AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
                                Thread.Sleep(500);
                                AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);



                                AGVForkSendCode(shRow, shCell, shFloor, 1);
                                AddListBak("取货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.startPosition);
                            }
                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 4)
                        {
                            if (!CTaskInfo.PLCSRMTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                             && x.taskType == 2
                             && x.taskGroup == CTaskInfo.CurrentTask.startLocGroup
                             && x.taskColl == CTaskInfo.CurrentTask.startLocColl
                             && x.taskFloor == CTaskInfo.CurrentTask.startLocFloor))
                            {
                                if (cTaskStatus.SRM_Get_Finish != 0)
                                {
                                    AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);//取货

                                }


                                short shRow = CTaskInfo.CurrentTask.startLocGroup;
                                short shCell = CTaskInfo.CurrentTask.startLocColl;
                                short shFloor = CTaskInfo.CurrentTask.startLocFloor;
                                AGVForkSendCode(shRow, shCell, shFloor, 2);
                                AddListBak("货叉取货任务下发完成,取货货位:" + CTaskInfo.CurrentTask.startPosition);
                                CTaskInfo.CurrentTask.forkHStatus = "0";
                            }
                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 5)
                        {
                            short shRow = CTaskInfo.CurrentTask.endLocGroup;
                            short shCell = CTaskInfo.CurrentTask.endLocColl;
                            short shFloor = CTaskInfo.CurrentTask.endLocFloor;
                            short shFloor1 = CTaskInfo.CurrentTask.startLocFloor;

                            if (!CTaskInfo.AGVTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                             && x.startAgvLoc == CTaskInfo.CurrentTask.startAgvLoc
                             && x.endAgvLoc == CTaskInfo.CurrentTask.endAgvLoc))
                            {
                                AddListBak("开始给AGV下发新任务" + CTaskInfo.CurrentTask.endAgvLoc);

                                AGVController.AgvModel.robot_base_res rbs = BasicInfo.AgvService.addTask(CTaskInfo.CurrentTask.startAgvLoc, CTaskInfo.CurrentTask.endAgvLoc);
                                if (rbs.ret_code == 0)
                                {
                                    currentAgvStatus.task_status = 0;
                                    AddListBak("AGV任务下发:" + CTaskInfo.CurrentTask.startPosition + "(" + CTaskInfo.CurrentTask.startAgvLoc + ")到" + CTaskInfo.CurrentTask.endPosition + "(" + CTaskInfo.CurrentTask.endAgvLoc + ")");
                                    UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 6);
                                    CTaskInfo.CurrentTask.taskStatus = 6;
                                    AddListBak("放货先货叉移动完成，状态变为:6");
                                    CTaskInfo.AGVTaskSendList.Add(new AGVTaskSend
                                    {
                                        taskCode = CTaskInfo.CurrentTask.taskCode,
                                        startAgvLoc = CTaskInfo.CurrentTask.startAgvLoc,
                                        endAgvLoc = CTaskInfo.CurrentTask.endAgvLoc
                                    });


                                    ////if (shFloor<3&& shFloor1<3)//小于4层可以行走中升降
                                    ////{
                                    if (CTaskInfo.CurrentTask.startAgvLoc != CTaskInfo.AgvGetSetPointLoc)
                                    {
                                        AGVForkSendCode(shRow, shCell, shFloor, 1);
                                        AddListBak("AGV任务下发移动命令后货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.endPosition);
                                    }
                                    ////}

                                }
                                else
                                {
                                    AddListBak("AGV任务下发失败," + CTaskInfo.CurrentTask.startAgvLoc + "-" + CTaskInfo.CurrentTask.endAgvLoc + ", 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                                    Thread.Sleep(1000 * 5);
                                }
                            }
                            else
                                AddListBak("CTaskInfo.CurrentTask.taskStatus == 5" + DateTime.Now.ToString("yyyyMMddHHmmss"));

                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 7)
                        {
                            if (!CTaskInfo.PLCSRMTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                             && x.taskType == 1
                             && x.taskGroup == CTaskInfo.CurrentTask.endLocGroup
                             && x.taskColl == CTaskInfo.CurrentTask.endLocColl
                             && x.taskFloor == CTaskInfo.CurrentTask.endLocFloor))
                            {
                                if (CTaskInfo.CurrentTask.forkHStatus != "2")
                                {
                                    short shRow = CTaskInfo.CurrentTask.endLocGroup;
                                    short shCell = CTaskInfo.CurrentTask.endLocColl;
                                    short shFloor = CTaskInfo.CurrentTask.endLocFloor;

                                    if (cTaskStatus.SRM_Task_Finish != 0)
                                    {
                                        AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);

                                    }

                                    AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);// 取消货叉任务
                                                                                                           //复位
                                    AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
                                    Thread.Sleep(500);
                                    AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);



                                    AGVForkSendCode(shRow, shCell, shFloor, 1);

                                    AddListBak("放货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.endPosition);
                                }
                            }
                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 8)
                        {
                            if (!CTaskInfo.PLCSRMTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                             && x.taskType == 3
                             && x.taskGroup == CTaskInfo.CurrentTask.endLocGroup
                             && x.taskColl == CTaskInfo.CurrentTask.endLocColl
                             && x.taskFloor == CTaskInfo.CurrentTask.endLocFloor))
                            {
                                //如果是放货申请点
                                if (CTaskInfo.SetGoodAppltLoc.Exists(x => x == CTaskInfo.CurrentTask.endAgvLoc))
                                {
                                    AddListBak("给WCS发送放货申请,放货货位:" + CTaskInfo.CurrentTask.endPosition);
                                    #region 给WCS发送放货申请
                                    try
                                    {
                                        WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                                        WCSService.Response response = sendToWcs.SendAgvSetGoodApply(CTaskInfo.AgvGetSetPointLoc, "setgood", CTaskInfo.CurrentTask.taskCode);
                                        if (response.code != "0")
                                        {//申请没有通过，继续
                                            AddListBak("给WCS发送放货申请没有通过," + response.message);
                                            continue;
                                        }
                                        else
                                        {
                                            AddListBak("给WCS发送放货申请通过,放货货位:" + CTaskInfo.CurrentTask.endPosition);
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        AddListBak("给WCS发送放货申请异常,放货货位:" + CTaskInfo.CurrentTask.endPosition + ex.Message);
                                        continue;

                                    }
                                    #endregion

                                }
                                if (cTaskStatus.SRM_Set_Finish != 0)
                                {
                                    AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1); ;//放货

                                }
                                short shRow = CTaskInfo.CurrentTask.endLocGroup;
                                short shCell = CTaskInfo.CurrentTask.endLocColl;
                                short shFloor = CTaskInfo.CurrentTask.endLocFloor;
                                AGVForkSendCode(shRow, shCell, shFloor, 3);
                                AddListBak("货叉放货任务下发完成,放货货位:" + CTaskInfo.CurrentTask.endPosition);
                            }
                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 9)
                        {
                            if (currentAgvStatus.current_station != CTaskInfo.AgvGetSetPointLoc)
                            {
                                if (!CTaskInfo.AGVTaskSendList.Exists(x => x.taskCode == CTaskInfo.CurrentTask.taskCode
                                 && x.startAgvLoc == CTaskInfo.CurrentTask.endAgvLoc
                                 && x.endAgvLoc == CTaskInfo.AgvGetSetPointLoc))
                                {
                                    AGVController.AgvModel.robot_base_res rbs = BasicInfo.AgvService.addTask(CTaskInfo.CurrentTask.endAgvLoc, CTaskInfo.AgvGetSetPointLoc);
                                    if (rbs.ret_code == 0)
                                    {
                                        currentAgvStatus.task_status = 0;
                                        AddListBak("AGV任务下发:" + CTaskInfo.CurrentTask.endPosition + "(" + CTaskInfo.CurrentTask.endAgvLoc + ")-(" + CTaskInfo.AgvGetSetPointLoc + ")");
                                        UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 10);
                                        CTaskInfo.CurrentTask.taskStatus = 10;

                                        CTaskInfo.AGVTaskSendList.Add(new AGVTaskSend
                                        {
                                            taskCode = CTaskInfo.CurrentTask.taskCode,
                                            startAgvLoc = CTaskInfo.CurrentTask.endAgvLoc,
                                            endAgvLoc = CTaskInfo.AgvGetSetPointLoc
                                        });

                                        // CTaskInfo.AgvGetSetPointLoc
                                        /// <summary>
                                        /// WCS发送的起始取货对应的排
                                        /// </summary>
                                        int startLocGroupTmp = 0;
                                        /// <summary>
                                        /// WCS发送的起始取货对应的列
                                        /// </summary>
                                        int startLocCollTmp = 0;
                                        /// <summary>
                                        /// WCS发送的起始取货对应的层
                                        /// </summary>
                                        int startLocFloorTmp = 0;




                                        bool blExist = false;
                                        string sql = " SELECT * FROM WCS_AGV_LOC WHERE AGV_LOC='" + CTaskInfo.AgvGetSetPointLoc + "';  ";
                                        DataSet dsAgvLoc = DbHelperSQLite.Query(sql);
                                        if (dsAgvLoc != null)
                                            if (dsAgvLoc.Tables.Count > 0)
                                                if (dsAgvLoc.Tables[0].Rows.Count > 0)
                                                {
                                                    startLocGroupTmp = int.Parse(dsAgvLoc.Tables[0].Rows[0]["LOC_GROUP"].ToString());
                                                    startLocCollTmp = int.Parse(dsAgvLoc.Tables[0].Rows[0]["LOC_COLL"].ToString());
                                                    startLocFloorTmp = int.Parse(dsAgvLoc.Tables[0].Rows[0]["LOC_FLOOR"].ToString());
                                                    blExist = true;
                                                }
                                        if (blExist)
                                        {
                                            short shRow = (short)startLocGroupTmp;
                                            short shCell = (short)startLocCollTmp;
                                            short shFloor = (short)startLocFloorTmp;

                                            //AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);// 取消货叉任务
                                            //                                                                       //复位
                                            //AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
                                            //Thread.Sleep(500);
                                            //AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);
                                            if (cTaskStatus.SRM_Task_Finish != 0)
                                            {
                                                AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);

                                            }
                                            AGVForkSendCode(shRow, shCell, shFloor, 1);
                                            AddListBak("放货前货叉移动任务下发完成,移动货位:" + CTaskInfo.CurrentTask.endPosition);
                                        }


                                    }
                                    else
                                    {
                                        AddListBak("AGV任务下发失败," + CTaskInfo.CurrentTask.endPosition + "(" + CTaskInfo.CurrentTask.startAgvLoc + ")-(" + CTaskInfo.AgvGetSetPointLoc + "), 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                                        Thread.Sleep(1000 * 5);
                                    }
                                }
                            }
                            else
                            {
                                UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 11);
                                CTaskInfo.CurrentTask.taskStatus = 11;

                                #region 给WCS发送任务完成
                                //WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                                //sendToWcs.SendAgvTaskStatus(CTaskInfo.AgvGetSetPointLoc, "finish", CTaskInfo.CurrentTask.taskCode);
                                #endregion
                            }
                        }
                        else if (CTaskInfo.CurrentTask.taskStatus == 11)
                        {

                            AddListBak("任务" + CTaskInfo.CurrentTask.taskCode + "执行完成");
                            UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 14);

                            #region 给WCS发送任务完成
                            WCSService.ToWCS.SendRequest sendToWcs = new WCSService.ToWCS.SendRequest(CTaskInfo.WCS_URL);
                            sendToWcs.SendAgvTaskStatus(CTaskInfo.AgvGetSetPointLoc, "finish", CTaskInfo.CurrentTask.taskCode);
                            #endregion
                            CTaskInfo.CurrentTask = null;
                            CTaskInfo.PLCSRMTaskSendList.Clear();
                            CTaskInfo.AGVTaskSendList.Clear();
                            FlushPage();
                        }
                    }
                    else
                    {
                        strWhere = "  taskStatus<=-10";
                        AGV.Model.WCS_AGV_TASK taskT = GetAgvTaskModel(strWhere);
                        if (taskT != null)
                        {
                            UpdateTaskStatus(taskT.taskCode, 1);
                        }

                    }

                    //---------------------------------end----------------------------------//
                }
                catch (Exception exc)
                {
                    AddListBak("系统控制线程数据处理错误," + exc.Message + exc.StackTrace + exc.Source);
                }

                Thread.Sleep(300);
            }
        }

        private void FlushPage()
        {
            lbTaskStatus.BeginInvoke(new EventHandler(delegate
            {
                lbTaskStatus.Text = "空闲";
                lbTaskStatus.BackColor = Color.Yellow;
           
                lbTaskFlag.Text = "";
           
                lbTaskNo.Text = "";
           
                lbTaskDateTime.Text = "";
           
                lbTaskGetLoc.Text = "";
           
                lbTaskSetLoc.Text = "";
            }));
        }

        private void FlushPageBack()
        {
            lbTaskStatus.BeginInvoke(new EventHandler(delegate
            {
                lbTaskStatus.Text = "空闲";
                lbTaskStatus.BackColor = Color.Yellow;
            }));
            lbTaskFlag.BeginInvoke(new EventHandler(delegate
            {
                lbTaskFlag.Text = "";
            }));
            lbTaskNo.BeginInvoke(new EventHandler(delegate
            {
                lbTaskNo.Text = "";
            }));
            lbTaskDateTime.BeginInvoke(new EventHandler(delegate
            {
                lbTaskDateTime.Text = "";
            }));
            lbTaskGetLoc.BeginInvoke(new EventHandler(delegate
            {
                lbTaskGetLoc.Text = "";
            }));
            lbTaskSetLoc.BeginInvoke(new EventHandler(delegate
            {
                lbTaskSetLoc.Text = "";
            }));
        }
        private void FlushPage(int mark)
        {
            if (mark > 0)
            {
                if (CTaskInfo.CurrentTask != null)
                {
                    string strTaskStatusTxt = GetTaskStatusTxt(CTaskInfo.CurrentTask.taskStatus);
                    bool blUpdate = false;
                    lbTaskStatus.BeginInvoke(new EventHandler(delegate
                    {
                        if (lbTaskStatus.Text != strTaskStatusTxt)
                        {
                            blUpdate = true;

                            lbTaskStatus.Text = strTaskStatusTxt;
                            lbTaskStatus.BackColor = Color.Green;

                            if (CTaskInfo.CurrentTask.taskCode != null)
                            {
                                lbTaskNo.Text = CTaskInfo.CurrentTask.taskCode;
                            }
                            else
                            {
                                lbTaskNo.Text = "";

                            }
                            if (CTaskInfo.CurrentTask.reqTime != null)
                            {
                                lbTaskDateTime.Text = CTaskInfo.CurrentTask.reqTime;
                            }
                            else
                            {
                                lbTaskDateTime.Text = "";
                            }

                            if (CTaskInfo.CurrentTask.startPosition != null)
                            {
                                lbTaskGetLoc.Text = CTaskInfo.CurrentTask.startPosition;
                            }
                            else
                            {
                                lbTaskGetLoc.Text = "";
                            }

                            if (CTaskInfo.CurrentTask.endPosition != null)
                            {
                                lbTaskSetLoc.Text = CTaskInfo.CurrentTask.endPosition;
                            }
                            else
                            {
                                lbTaskSetLoc.Text = "";
                            }
                            if (CTaskInfo.CurrentTask.startAgvLoc == CTaskInfo.AgvGetSetPointLoc)
                                lbTaskFlag.Text = "入库";
                            else if (CTaskInfo.CurrentTask.endAgvLoc == CTaskInfo.AgvGetSetPointLoc)
                                lbTaskFlag.Text = "出库";
                        }
                    }
                        ));

                }
            }
        }
        private void FlushPageBack(int mark)
        {
            if (mark > 0)
            {
                if(CTaskInfo.CurrentTask!=null)
                {
                    string strTaskStatusTxt = GetTaskStatusTxt(CTaskInfo.CurrentTask.taskStatus);
                    bool blUpdate = false;
                    lbTaskStatus.BeginInvoke(new EventHandler(delegate
                    {
                        if (lbTaskStatus.Text != strTaskStatusTxt)
                        {
                            blUpdate = true;
                        }
                    }));
                    if (blUpdate)
                    {
                        lbTaskStatus.BeginInvoke(new EventHandler(delegate
                        {
                            lbTaskStatus.Text = strTaskStatusTxt;
                            lbTaskStatus.BackColor = Color.Green;
                        }));
                        lbTaskFlag.BeginInvoke(new EventHandler(delegate
                        {
                            lbTaskFlag.Text = "";
                        }));
                        lbTaskNo.BeginInvoke(new EventHandler(delegate
                        {
                            lbTaskNo.Text = CTaskInfo.CurrentTask.taskCode;
                        }));
                        lbTaskDateTime.BeginInvoke(new EventHandler(delegate
                        {
                            lbTaskDateTime.Text = CTaskInfo.CurrentTask.reqTime;
                        }));
                        lbTaskGetLoc.BeginInvoke(new EventHandler(delegate
                        {
                            lbTaskGetLoc.Text = CTaskInfo.CurrentTask.startPosition;
                        }));
                        lbTaskSetLoc.BeginInvoke(new EventHandler(delegate
                        {
                            lbTaskSetLoc.Text = CTaskInfo.CurrentTask.endPosition;
                        }));
                    }
                }
            }
        }

        private string GetTaskStatusTxt(int statusCode)
        {  
            string strStatusTxt = "空闲";
            switch(statusCode)
            {
                case 0:
                    strStatusTxt = "空闲";
                    break;
                case 1:
                    strStatusTxt = "待执行";
                    break;
                case 2:
                    strStatusTxt = "取货行走中";
                    break;
                case 3:
                    strStatusTxt = "到达取货位";
                    break;
                case 4:
                    strStatusTxt = "取货货叉移动完成";
                    break;
                case -4:
                    strStatusTxt = "取货行走中货叉移动完成";
                    break;
                case 5:
                    strStatusTxt = "取货完成";
                    break;
                case 6:
                    strStatusTxt = "放货行走中";
                    break;
                case 7:
                    strStatusTxt = "到达放货位";
                    break;
                case 8:
                    strStatusTxt = "放货货叉移动完成";
                    break;
                case -8:
                    strStatusTxt = "放货行走中货叉移动完成";
                    break;
                case 9:
                    strStatusTxt = "放货完成";
                    break;
                case 10:
                    strStatusTxt = "放货返回移动中";
                    break;
                case 11:
                    strStatusTxt = "任务完成";
                    break;
                case 12:
                    strStatusTxt = "任务手动完成";
                    break;
                case 13:
                    strStatusTxt = "任务强制完成";
                    break;
                case 14:
                    strStatusTxt = "任务完成";
                    break;
                case 100:
                    strStatusTxt = "任务取消";
                    break;
            }
            return strStatusTxt;
        }
        #endregion

        #region WCS串口交互控制

        private void InitCom()
        {
            try
            {
                string sReadTemp = iniFile.IniReadValue("PLC_SRM1", "IP");
                string PLC_DQG_IP = string.IsNullOrWhiteSpace(sReadTemp) ? "192.168.0.8" : sReadTemp;
                sReadTemp = iniFile.IniReadValue("PLC_SRM1", "Port");
                string PLC_DQG_Port = string.IsNullOrWhiteSpace(sReadTemp) ? "102" : sReadTemp;
                sReadTemp = iniFile.IniReadValue("PLC_SRM1", "Rack");
                string PLC_DQG_Rack = string.IsNullOrWhiteSpace(sReadTemp) ? "0" : sReadTemp;
                sReadTemp = iniFile.IniReadValue("PLC_SRM1", "Slot");
                string PLC_DQG_Slot = string.IsNullOrWhiteSpace(sReadTemp) ? "1" : sReadTemp;

                PLCMsgModel plcmm = plcSRM1.PLCInit(PLC_DQG_IP, PLC_DQG_Port, PLC_DQG_Rack, PLC_DQG_Slot);
                if (plcmm.Code == 1)
                {
                    //初始化连接成功
                    AddListBak("货叉PLC连接成功！");
                    InitSRM1ComFlag = 1;

                    AddToPLCSRMDataList(cTaskStatus.SRM_RemoteAuto_ToPlc_Addr, 1, 1, 1, 1);
                }
                else
                {
                    AddListBak("货叉PLC连接失败！" + plcmm.Msg);
                }
                Thread.Sleep(500);
            }
            catch (Exception ex)
            {
                AddListBak("货叉PLC连接异常！" + ex.Message);
            }

        }

        #endregion

        #region 货叉控制线程

        /// <summary>
        /// 添加到List
        /// </summary>
        /// <param name="addr">地址</param>
        /// <param name="ReadOrWrite">读取或者写入 Read:0 Write:1</param>
        /// <param name="val">具体值</param>
        /// <param name="valType">值类型 bool:0  short:1</param>
        /// <param name="arrayLen">读取的数据长度</param>
        private void AddToPLCSRMDataList(string addr, short ReadOrWrite, object val, short valType, ushort arrayLen)
        {
            CTaskInfo.PLCSRMWirteDataList.Add(new Smart200Data
            {
                addr = addr,
                val = val,
                valtype = valType,
                read = ReadOrWrite,
                arraylen = arrayLen
            });
        }

        /// <summary>
        /// 堆垛机1读取指令下发
        /// </summary>
        private void UnitPLCSRM_Read()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;

                try
                {
                    if (CTaskInfo.PLCSRMWirteDataList.Count > 0)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    //判断是否有其它信息发送
                    if (CTaskInfo.PLCSRMReadDataList.Count > 0)
                    {
                        PLCMsgModel plcMM = new PLCMsgModel();
                        Smart200Data senddata = CTaskInfo.PLCSRMReadDataList[0];

                        if (senddata.read == 0)
                        {
                            //读取
                            if (senddata.valtype == 0)
                            {
                                plcMM = plcSRM1.PLCReadBool(senddata.addr);
                                //读取bool值
                                if (plcMM.Code == 1)
                                {
                                    if (plcMM.Val == null) continue;
                                    bool bRead = (bool)plcMM.Val;

                                    if (senddata.addr == cTaskStatus.SRM_Hearbeat_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Heartbeat = bRead ? 1 : 0;

                                        if (cTaskStatus.SRM_Heartbeat == 1)
                                        {
                                            lbForkHearbeat.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkHearbeat.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Heartbeat == 0)
                                        {
                                            lbForkHearbeat.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkHearbeat.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_RemoteAuto_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_RemoteAuto = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_RemoteAuto == 1)
                                        {
                                            lbForkRemoteAuto.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkRemoteAuto.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_RemoteAuto == 0)
                                        {
                                            lbForkRemoteAuto.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkRemoteAuto.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Alarm_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Alarm = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_Alarm == 1)
                                        {
                                            lbForkAlarm.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkAlarm.BackColor = Color.Red;
                                            }));

                                            lbForkAlarmInfo.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkAlarmInfo.BackColor = Color.Red;
                                                lbForkAlarmInfo.Text = GetForkAlarmTxt(cTaskStatus.SRM_BreakDownInfo);
                                            }));

                                        }
                                        else if (cTaskStatus.SRM_Alarm == 0)
                                        {
                                            lbForkAlarm.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkAlarm.BackColor = Color.LightSteelBlue;
                                            }));

                                            lbForkAlarmInfo.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkAlarmInfo.BackColor = Color.LightSteelBlue;
                                                lbForkAlarmInfo.Text = "无";
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_ForkIsHasGoods_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_ForkIsHasGood = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_ForkIsHasGood == 1)
                                        {
                                            lbForkHasGoods.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkHasGoods.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_ForkIsHasGood == 0)
                                        {
                                            lbForkHasGoods.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkHasGoods.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_ForkInZero_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_ForkInZero = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_ForkInZero == 1)
                                        {
                                            lbForkInZero.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkInZero.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_ForkInZero == 0)
                                        {
                                            lbForkInZero.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkInZero.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Task_Finished_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Task_Finish = bRead ? 1 : 0;

                                        if (cTaskStatus.SRM_Task_Finish == 1)
                                        {
                                            lbForkTaskFinished.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkTaskFinished.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Task_Finish == 0)
                                        {
                                            lbForkTaskFinished.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkTaskFinished.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                        AddListBak_Fork("货叉PLC读取任务完成:" + senddata.addr + "=" + (bRead ? "1" : "0"));
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Get_Finished_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Get_Finish = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_Get_Finish == 1)
                                        {
                                            lbForkGetFinished.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkGetFinished.BackColor = Color.Lime;
                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Get_Finish == 0)
                                        {
                                            lbForkGetFinished.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkGetFinished.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    else if (senddata.addr == cTaskStatus.SRM_Set_Finished_ToWcs_Addr)
                                    {
                                        cTaskStatus.SRM_Set_Finish = bRead ? 1 : 0;
                                        if (cTaskStatus.SRM_Set_Finish == 1)
                                        {
                                            lbForkSetFinished.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkSetFinished.BackColor = Color.Lime;

                                            }));
                                        }
                                        else if (cTaskStatus.SRM_Set_Finish == 0)
                                        {
                                            lbForkSetFinished.BeginInvoke(new EventHandler(delegate
                                            {
                                                lbForkSetFinished.BackColor = Color.LightSteelBlue;
                                            }));
                                        }
                                    }
                                    CTaskInfo.PLCSRMReadDataList.RemoveAt(0);

                                    AddListBak_Fork("货叉PLC读取 :" + senddata.addr + "=" + (bRead ? "1" : "0"));
                                }
                            }
                            else if (senddata.valtype == 1)
                            {
                                plcMM = plcSRM1.PLCReadByte(senddata.addr);
                                //读取short值
                                if (plcMM.Code == 1)
                                {
                                    if (plcMM.Val == null) continue;
                                    short bRead = (short)(plcMM.Val);
                                    CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                }
                            }
                            else if (senddata.valtype == 2)
                            {
                                plcMM = plcSRM1.PLCReadInt(senddata.addr);
                                //读取int值
                                if (plcMM.Code == 1)
                                {
                                    if (plcMM.Val == null) continue;
                                    object objBreakdown = plcMM.Val;
                                    CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                }
                            }
                            else if (senddata.valtype == 3)
                            {
                                if (senddata.arraylen > 0)
                                {
                                    plcMM = plcSRM1.PLCReadBoolArray(senddata.addr, senddata.arraylen);
                                    if (plcMM.Code == 1)
                                    {
                                        if (plcMM.Val == null) continue;
                                        CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                    }
                                }
                            }
                            else if (senddata.valtype == 4)
                            {
                                if (senddata.arraylen > 0)
                                {
                                    plcMM = plcSRM1.PLCReadByte(senddata.addr, senddata.arraylen);
                                    if (plcMM.Code == 1)
                                    {
                                        if (plcMM.Val == null) continue;
                                        short[] bRead = (short[])plcMM.Val;
                                        if (senddata.addr == cTaskStatus.SRM_AlarmCode_ToWcs_Addr)
                                        {
                                            cTaskStatus.SRM_BreakDownInfo = bRead[0];
                                            cTaskStatus.SRM_Status = bRead[1];
                                            cTaskStatus.SRM_Pos_Row = bRead[2];
                                            cTaskStatus.SRM_Pos_Floor = bRead[3];


                                            if (cTaskStatus.SRM_Status == 1)
                                            {
                                                lbForkStatus.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkStatus.BackColor = Color.Lime;
                                                    lbForkStatus.Text = "运行";
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Status == 0)
                                            {
                                                lbForkStatus.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkStatus.BackColor = Color.LightSteelBlue;
                                                    lbForkStatus.Text = "空闲";
                                                }));
                                            }

                                            if (cTaskStatus.SRM_Pos_Row > 0)
                                            {
                                                lbForkPosRow.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkPosRow.BackColor = Color.Lime;
                                                    lbForkPosRow.Text = cTaskStatus.SRM_Pos_Row.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Pos_Row == 0)
                                            {
                                                lbForkPosRow.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkPosRow.BackColor = Color.LightSteelBlue;
                                                    lbForkPosRow.Text = "0";
                                                }));
                                            }
                                            if (cTaskStatus.SRM_Pos_Floor > 0)
                                            {
                                                lbForkPosFloor.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkPosFloor.BackColor = Color.Lime;
                                                    lbForkPosFloor.Text = cTaskStatus.SRM_Pos_Floor.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Pos_Row == 0)
                                            {
                                                lbForkPosFloor.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkPosFloor.BackColor = Color.LightSteelBlue;
                                                    lbForkPosFloor.Text = "0";
                                                }));
                                            }
                                        }
                                        else if (senddata.addr == cTaskStatus.SRM_TaskID_ToWcs_Addr)
                                        {
                                            cTaskStatus.SRM_Task_ID = bRead[0];

                                            cTaskStatus.SRM_GetGoodsApply = bRead[3];
                                            cTaskStatus.SRM_SetGoodsApply = bRead[4];

                                            if (cTaskStatus.SRM_Task_ID > 0)
                                            {
                                                lbForkTaskID.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkTaskID.BackColor = Color.Lime;
                                                    lbForkTaskID.Text = cTaskStatus.SRM_Task_ID.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_Task_ID == 0)
                                            {
                                                lbForkTaskID.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbForkTaskID.BackColor = Color.LightSteelBlue;
                                                    lbForkTaskID.Text = "0";
                                                }));
                                            }



                                            if (cTaskStatus.SRM_GetGoodsApply > 0)
                                            {
                                                lbGetGoodsApply.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbGetGoodsApply.BackColor = Color.Lime;
                                                    lbGetGoodsApply.Text = cTaskStatus.SRM_Task_ID.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_GetGoodsApply == 0)
                                            {
                                                lbGetGoodsApply.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbGetGoodsApply.BackColor = Color.LightSteelBlue;
                                                    lbGetGoodsApply.Text = "0";
                                                }));
                                            }
                                            if (cTaskStatus.SRM_SetGoodsApply > 0)
                                            {
                                                lbSetGoodsApply.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbSetGoodsApply.BackColor = Color.Lime;
                                                    lbSetGoodsApply.Text = cTaskStatus.SRM_Task_ID.ToString();
                                                }));
                                            }
                                            else if (cTaskStatus.SRM_SetGoodsApply == 0)
                                            {
                                                lbSetGoodsApply.BeginInvoke(new EventHandler(delegate
                                                {
                                                    lbSetGoodsApply.BackColor = Color.LightSteelBlue;
                                                    lbSetGoodsApply.Text = "0";
                                                }));
                                            }
                                        }
                                        CTaskInfo.PLCSRMReadDataList.RemoveAt(0);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        Smart200Data tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Hearbeat_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_ForkIsHasGoods_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_ForkInZero_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Alarm_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_AlarmCode_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 4;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 4;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);

                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Get_Finished_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Set_Finished_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_RemoteAuto_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_Task_Finished_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 0;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 1;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                        tmpsenddata = new Smart200Data();
                        tmpsenddata.addr = cTaskStatus.SRM_TaskID_ToWcs_Addr;
                        tmpsenddata.read = 0;
                        tmpsenddata.valtype = 4;
                        tmpsenddata.val = 0;
                        tmpsenddata.arraylen = 5;
                        CTaskInfo.PLCSRMReadDataList.Add(tmpsenddata);
                    }

                    //---------------------------------end----------------------------------//
                }
                catch (Exception s)
                {
                    AddListBak("货叉PLC读取线程异常:" + s.Message + s.StackTrace);
                }
                Thread.Sleep(50);
            }
        }

        private string GetForkAlarmTxt(int AlarmID)
        {
            string strTxt = "";
            switch (AlarmID)
            {
                case 1:
                    strTxt = AlarmID.ToString() + ":空出";
                    break;
                case 2:
                    strTxt = AlarmID.ToString() + ":满入";
                    break;
                case 3:
                    strTxt = AlarmID.ToString() + ":任务下发错误";
                    break;
                case 4:
                    strTxt = AlarmID.ToString() + ":取货时货叉有货";
                    break;
                case 5:
                    strTxt = AlarmID.ToString() + ":放货时货叉无货";
                    break;
                case 6:
                    strTxt = AlarmID.ToString() + ":升降定位失败";
                    break;
                case 7:
                    strTxt = AlarmID.ToString() + ":货叉定位失败";
                    break;
                case 8:
                    strTxt = AlarmID.ToString() + ":货叉数据异常或者卡阻";
                    break;
                case 9:
                    strTxt = AlarmID.ToString() + ":升降数据异常或者卡阻";
                    break;
                case 10:
                    strTxt = AlarmID.ToString() + ":货叉运行超时";
                    break;
                case 11:
                    strTxt = AlarmID.ToString() + ":货叉起叉超时";
                    break;
                case 12:
                    strTxt = AlarmID.ToString() + ":货叉落叉超时";
                    break;
                case 13:
                    strTxt = AlarmID.ToString() + ":升降极限";
                    break;
                case 14:
                    strTxt = AlarmID.ToString() + ":急停";
                    break;
                case 15:
                    strTxt = AlarmID.ToString() + ":货叉变频器故障";
                    break;
                case 16:
                    strTxt = AlarmID.ToString() + ":升降变频器故障";
                    break;
                case 17:
                    strTxt = AlarmID.ToString() + ":左超宽";
                    break;
                case 18:
                    strTxt = AlarmID.ToString() + ":右超宽";
                    break;
            }
            return strTxt;

        }

        /// <summary>
        /// 产线写入指令下发
        /// </summary>
        private void UnitPLCSRM_Write()
        {
            while (true)
            {
                //线程退出
                if (allThreadValue == 1) break;

                try
                {
                    //-------------------------------发送数据--------------------------------//
                    //判断是否有其它信息发送
                    if (CTaskInfo.PLCSRMWirteDataList != null)
                    {
                        if (CTaskInfo.PLCSRMWirteDataList.Count > 0)
                        {
                            PLCMsgModel plcMM = new PLCMsgModel();
                            Smart200Data senddata = CTaskInfo.PLCSRMWirteDataList[0];
                            if (senddata == null)
                            {
                                AddListBak_Fork("货叉PLC写入UnitPLCSRM_Write 为空");

                            }
                            if (senddata.val == null)
                            {
                                AddListBak_Fork("货叉PLC写入 :" + senddata.addr + "=为空---" + senddata.read);
                                CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);
                                continue;
                            }
                            AddListBak_Fork("货叉PLC写入 :" + senddata.addr + "=" + senddata.val.ToString() + "---" + senddata.read);
                            if (senddata.read == 0)
                            {

                                AddListBak_Fork("货叉PLC写入出现读取指令 :" + senddata.addr + "=" + senddata.val.ToString() + "---" + senddata.read);
                                CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);
                                continue;

                                //读取
                            }
                            else if (senddata.read == 1)
                            {
                                bool blSendValue = false;
                                short shSendValue = 0;
                                //写入
                                if (senddata.valtype == 0)
                                {
                                    blSendValue = Convert.ToInt16(senddata.val) == 1 ? true : false;
                                    plcMM = plcSRM1.PLCWrite(senddata.addr, blSendValue);
                                    //读取short值
                                    if (plcMM.Code == 1)
                                    {
                                        CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);
                                    }
                                    else
                                    {
                                        AddListBak_Fork("货叉PLC写入失败 :" + senddata.addr + "=" + senddata.val.ToString() + plcMM.Msg);

                                    }
                                }
                                else if (senddata.valtype == 1)
                                {
                                    shSendValue = Convert.ToInt16(senddata.val);
                                    plcMM = plcSRM1.PLCWrite(senddata.addr, shSendValue);
                                    //读取short值
                                    if (plcMM.Code == 1)
                                    {
                                        CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);
                                    }
                                    else
                                    {

                                        AddListBak_Fork("货叉PLC写入失败 :" + senddata.addr + "=" + senddata.val.ToString() + plcMM.Msg);
                                    }
                                }
                                else
                                {
                                    CTaskInfo.PLCSRMWirteDataList.RemoveAt(0);

                                    AddListBak_Fork("货叉PLC写入数据类型有误 :" + senddata.addr + "=" + senddata.val.ToString() + "\\" + senddata.valtype);
                                }


                            }
                        }
                    }
                    //---------------------------------end----------------------------------//
                }
                catch (NullReferenceException nu)
                {
                    AddListBak("货叉写入线程异常:" + nu.GetType() + nu.Message + nu.Source + nu.StackTrace+ nu.TargetSite.ToString());
                }
                catch (Exception s)
                {
                    AddListBak("货叉写入线程异常:" + s.GetType() + s.Message + s.Source + s.StackTrace);
                    if (s.InnerException != null)
                    {
                        AddListBak("货叉写入线程异常:" + s.InnerException.GetType() + s.InnerException.Message + s.InnerException.Source + s.InnerException.StackTrace);

                    }
                }
                Thread.Sleep(100);
            }
        }
        #endregion

        #region 初始化变量
        /// <summary>
        /// 初始化全局变量
        /// </summary>
        private void InitGlobalVariable()
        {
            #region 读取配置文件 
            try
            {
                CTaskInfo.AGV_URL = iniFile.IniReadValue("SysInfo", "AGV_URL") == "" ? "" : iniFile.IniReadValue("SysInfo", "AGV_URL");
                CTaskInfo.WCS_URL = iniFile.IniReadValue("SysInfo", "WCS_URL") == "" ? "" : iniFile.IniReadValue("SysInfo", "WCS_URL");
                CTaskInfo.AgvGetSetPointLoc = iniFile.IniReadValue("SysInfo", "Agv_GetSetPointLoc") == "" ? "" : iniFile.IniReadValue("SysInfo", "Agv_GetSetPointLoc");
                CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo") == "" ? "" : iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                CTaskInfo.WareName = iniFile.IniReadValue("SysInfo", "WareName");
                CTaskInfo.AgvAutoChangeLowValue = iniFile.IniReadValue("SysInfo", "AgvAutoChangeLowValue");
                CTaskInfo.AgvChargingLoc = iniFile.IniReadValue("SysInfo", "AgvChargingLoc");

                string setGoodAppltLoc = iniFile.IniReadValue("SysInfo", "SetGoodAppltLoc");
                CTaskInfo.SetGoodAppltLoc =new List<string>( setGoodAppltLoc.Split(new char[] {',' },StringSplitOptions.RemoveEmptyEntries));
            }
            catch (Exception exc)
            {
                AddListBak("获取系统配置异常，请检查系统配置文件");
            }
            #endregion
        }
        #endregion

        #region 日志存储

        //跨线程访问listbox控件
        delegate void AddList();
        private void AddListBak(string s)
        {
            // 将委托实例化 
            AddList a = delegate ()
            {
                if (listBoxSysRunLog.Items.Count > 0)
                {
                    if (listBoxSysRunLog.Items[0].ToString().Split(']')[1] == s) return;
                }
                if (listBoxSysRunLog.Items.Count > 1000) listBoxSysRunLog.Items.Clear();
                listBoxSysRunLog.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + s);
                Log.saveToLog(Log.locType.Sys,"[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]-" + s);
                listBoxSysRunLog.Refresh();
            };
            listBoxSysRunLog.BeginInvoke(a);

        }


        private void AddListBak_Agv(string s)
        {

            tabControl1.BeginInvoke(new EventHandler(delegate
            {
                if (tabControl1.SelectedIndex == 1)
                {
                    if (!s.Contains("percentage") && (!s.Contains("position") && !s.Contains("orientation")))
                    {
                        //listBoxAgvControlLog.BeginInvoke(new EventHandler(delegate
                        //{

                            if (listBoxAgvControlLog.Items.Count > 0)
                            {
                                if (listBoxAgvControlLog.Items[0].ToString().Split(']')[1] == s) return;
                            }
                            if (listBoxAgvControlLog.Items.Count > 1000) listBoxAgvControlLog.Items.Clear();
                            listBoxAgvControlLog.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + s);
                            listBoxAgvControlLog.Refresh();

                        //}));
                    }
                }
                else
                {
                    if (!s.Contains("percentage")&& (!s.Contains("position") && !s.Contains("orientation")))
                    {
                        // 将委托实例化 
                        //AddList a = delegate ()
                        //{
                            if (listBoxAgv.Items.Count > 0)
                            {
                                if (listBoxAgv.Items[0].ToString().Split(']')[1] == s) return;
                            }
                            if (listBoxAgv.Items.Count > 1000) listBoxAgv.Items.Clear();
                            listBoxAgv.Items.Insert(0, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + s);
                            listBoxAgv.Refresh();
                        //};
                        //listBoxAgv.BeginInvoke(a);
                    }
                }
            }));

            try
            {
                if (!s.Contains("percentage") && (!s.Contains("position") && !s.Contains("orientation")))
                {
                    Log.saveToLog(Log.locType.Agv, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]-" + s);
                }
            }
            catch
            {

            }
        }


        private void AddListBak_Fork(string s)
        {
            try
            {
                Log.saveToLog(Log.locType.Fork, "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]-" + s);

            }
            catch
            {

            }
        }

        #endregion


        #region AGV操作信息

        /// <summary>
        /// 更新数据库中任务状态
        /// </summary>
        /// <param name="taskno"></param>
        /// <param name="status">AGV实时任务状态 0：空闲 /1：待执行/2：取货行走中/3:到达取货位/4：取货货叉移动完成/5：取货完成/6：放货行走中/7：到达放货位/8：放货货叉移动完成/9：放货完成/10：放货返回移动中/11：任务完成(到达默认位置)/12:任务手动完成 /13:任务强制完成/100:任务取消</param>
        /// <returns></returns>
        private int UpdateTaskStatus(string taskno, int status)
        {
            AddListBak("更新状态=" + status.ToString());
            string strSql = "UPDATE WCS_AGV_TASK SET taskStatus=" + status.ToString() + " WHERE taskCode='" + taskno.ToString()+"'";
            return DbHelperSQLite.ExecuteSql(strSql);            
        }


        private int DeleteTask(string taskno)
        {
            AddListBak("手动删除任务=" + taskno);
            string strSql = "DELETE FROM WCS_AGV_TASK   WHERE taskCode='" + taskno.ToString()+"'";
            return DbHelperSQLite.ExecuteSql(strSql);
        }

        #region 获取任务Model

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public AGV.Model.WCS_AGV_TASK GetAgvTaskModel(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select id,taskCode,reqCode,reqTime,startPosition,endPosition,priority,taskStatus,startLocGroup,startLocColl,startLocFloor,endLocGroup,endLocColl,endLocFloor,startAgvLoc,endAgvLoc from WCS_AGV_TASK ");
            if (strWhere != "")
                strSql.Append(" where " + strWhere);
            strSql.Append(" ORDER BY  id ");
            AGV.Model.WCS_AGV_TASK model = new AGV.Model.WCS_AGV_TASK();
            DataSet ds = DbHelperSQLite.Query(strSql.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToAgvTaskModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public DataSet GetAgvTasks(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select id,taskCode,reqCode,reqTime,startPosition,endPosition,priority,taskStatus,startLocGroup,startLocColl,startLocFloor,endLocGroup,endLocColl,endLocFloor,startAgvLoc,endAgvLoc" +
                ", CASE WHEN startAgvLoc='LM1' THEN '入库' ELSE '出库' END AS TASK_FLAG_NAME " +
                ",CASE WHEN taskStatus=0 THEN '空闲' WHEN taskStatus = 1 THEN '待执行' " +
                " WHEN taskStatus = 2 THEN '取货行走中' WHEN taskStatus = 3 THEN '到达取货位'" +
                " WHEN taskStatus = 4 THEN '取货货叉移动完成' WHEN taskStatus = -4 THEN '取货行走中货叉移动完成'" +
                " WHEN taskStatus = 5 THEN '取货完成' WHEN taskStatus = 6 THEN '放货行走中' " +
                " WHEN taskStatus = 7 THEN '到达放货位' WHEN taskStatus = 8 THEN '放货货叉移动完成' " +
                " WHEN taskStatus = -8 THEN '放货行走中货叉移动完成' WHEN taskStatus = 9 THEN '放货完成' " +
                " WHEN taskStatus = 10 THEN '放货返回移动中' WHEN taskStatus = 11 THEN '任务完成' " +
                " WHEN taskStatus = 12 THEN '任务手动完成' WHEN taskStatus = 13 THEN '任务强制完成' " +
                " WHEN taskStatus = 14 THEN '任务完成' WHEN taskStatus = 100 THEN '任务取消' " +
                " END AS taskStatusName " +
                " from WCS_AGV_TASK ");
            if (strWhere != "")
                strSql.Append(" where " + strWhere);
            strSql.Append(" ORDER BY  id ");
            AGV.Model.WCS_AGV_TASK model = new AGV.Model.WCS_AGV_TASK();
            DataSet ds = DbHelperSQLite.Query(strSql.ToString());
            if (ds.Tables[0].Rows.Count > 0)
            {
                return ds;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public AGV.Model.WCS_AGV_TASK DataRowToAgvTaskModel(DataRow row)
        {
            AGV.Model.WCS_AGV_TASK model = new AGV.Model.WCS_AGV_TASK();
            if (row != null)
            {
                if (row["id"] != null && row["id"].ToString() != "")
                {
                    model.id = int.Parse(row["id"].ToString());
                }
                if (row["taskCode"] != null)
                {
                    model.taskCode = row["taskCode"].ToString();
                }
                if (row["reqCode"] != null)
                {
                    model.reqCode = row["reqCode"].ToString();
                }
                if (row["reqTime"] != null)
                {
                    model.reqTime = row["reqTime"].ToString();
                }
                if (row["startPosition"] != null)
                {
                    model.startPosition = row["startPosition"].ToString();
                }
                if (row["endPosition"] != null)
                {
                    model.endPosition = row["endPosition"].ToString();
                }
                if (row["priority"] != null)
                {
                    model.priority = row["priority"].ToString();
                }
                if (row["taskStatus"] != null && row["taskStatus"].ToString() != "")
                {
                    model.taskStatus = int.Parse(row["taskStatus"].ToString());
                }
                if (row["startLocGroup"] != null && row["startLocGroup"].ToString() != "")
                {
                    model.startLocGroup = short.Parse(row["startLocGroup"].ToString());
                }
                if (row["startLocColl"] != null && row["startLocColl"].ToString() != "")
                {
                    model.startLocColl = short.Parse(row["startLocColl"].ToString());
                }
                if (row["startLocFloor"] != null && row["startLocFloor"].ToString() != "")
                {
                    model.startLocFloor = short.Parse(row["startLocFloor"].ToString());
                }
                if (row["endLocGroup"] != null && row["endLocGroup"].ToString() != "")
                {
                    model.endLocGroup = short.Parse(row["endLocGroup"].ToString());
                }
                if (row["endLocColl"] != null && row["endLocColl"].ToString() != "")
                {
                    model.endLocColl = short.Parse(row["endLocColl"].ToString());
                }
                if (row["endLocFloor"] != null && row["endLocFloor"].ToString() != "")
                {
                    model.endLocFloor = short.Parse(row["endLocFloor"].ToString());
                }
                if (row["startAgvLoc"] != null)
                {
                    model.startAgvLoc = row["startAgvLoc"].ToString();
                }
                if (row["endAgvLoc"] != null)
                {
                    model.endAgvLoc = row["endAgvLoc"].ToString();
                }
            }
            return model;
        }
        #endregion
        #endregion


        #region 货叉信息交互
        ushort usTaskID = 100;
        /// <summary>
        /// 货叉任务下发
        /// </summary>
        /// <param name="setRow">目标排</param>
        /// <param name="setColl">目标列</param>
        /// <param name="setFloor">目标层</param>
        /// <param name="taskType">任务类型 1:移动任务 2:取货任务 3:放货任务</param>
        private void AGVForkSendCode(short setRow, short setColl, short setFloor, short taskType)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_SetRow_ToPlc_Addr, 1, setRow, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_SetColl_ToPlc_Addr, 1, setColl, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_SetFloor_ToPlc_Addr, 1, setFloor, 1, 1);
            if (usTaskID > 30000)
                usTaskID = 100;
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, usTaskID, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskType_ToPlc_Addr, 1, taskType, 1, 1);
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskType_ToPlc_Addr, 1, taskType, 1, 1);
           // Thread.Sleep(100);
            AddToPLCSRMDataList(cTaskStatus.SRM_TaskStartFlag_ToPlc_Addr, 1, 1, 1, 1);

            AddListBak("给货叉Plc下发新任务,任务号:" + usTaskID.ToString() + "任务类型(1=移动,2=取货,3=放货):" + taskType.ToString() + "排=" + setRow.ToString() + ",列=" + setColl.ToString() + ",层=" + setFloor.ToString());

            if(CTaskInfo.CurrentTask!=null)
            {
                SRMTaskSend srmTaskSend = new SRMTaskSend();
                srmTaskSend.taskCode = CTaskInfo.CurrentTask.taskCode;
                srmTaskSend.taskType = taskType;
                srmTaskSend.taskId = usTaskID;
                srmTaskSend.taskGroup = setRow;
                srmTaskSend.taskColl = setColl;
                srmTaskSend.taskFloor = setFloor;
                CTaskInfo.PLCSRMTaskSendList.Add(srmTaskSend);
            }

            usTaskID++;
        }
        #endregion

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (BasicInfo.AgvService.AgvConneed)
                AddListBak_Agv("AGV已经成功连接");
            else
                BasicInfo.AgvService = new AgvHelper(iniFile.IniReadValue("ForAgv", "AgvIP"));

        }

        private void btnDisCon_Click(object sender, EventArgs e)
        {

        }

        private void btnSendTask_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(cmbStartWcsLocNo.Text.Trim())&& !string.IsNullOrEmpty(cmbEndWcsLocNo.Text.Trim()))
            {

                string startAgvLoc = "";
                string endAgvLoc = "";
                bool blExist = false;
                string sql = " SELECT * FROM WCS_AGV_LOC WHERE WCS_LOC='" + cmbStartWcsLocNo.Text.Trim() + "';  ";
                DataSet dsAgvLoc = DbHelperSQLite.Query(sql);
                if (dsAgvLoc != null)
                    if (dsAgvLoc.Tables.Count > 0)
                        if (dsAgvLoc.Tables[0].Rows.Count > 0)
                        {
                            startAgvLoc = dsAgvLoc.Tables[0].Rows[0]["Agv_Loc"].ToString();
                            blExist = true;
                        }
                if (!blExist)
                {
                    AddListBak_Agv("起始储位对应的AGV储位不存在!"); 
                }
                else
                {
                    blExist = false;
                    sql = " SELECT * FROM WCS_AGV_LOC WHERE WCS_LOC='" + cmbEndWcsLocNo.Text.Trim()+ "';  ";
                    DataSet dsAgvLocEnd = DbHelperSQLite.Query(sql);
                    if (dsAgvLocEnd != null)
                        if (dsAgvLocEnd.Tables.Count > 0)
                            if (dsAgvLocEnd.Tables[0].Rows.Count > 0)
                            {
                                endAgvLoc = dsAgvLocEnd.Tables[0].Rows[0]["Agv_Loc"].ToString();
                                blExist = true;
                            }
                    if (!blExist)
                    {
                        AddListBak_Agv("终止储位对应的AGV储位不存在!");
                    }
                    else
                    {
                        AGVController.AgvModel.robot_base_res rbs = new AGVController.AgvModel.robot_base_res();
                        //if (currentAgvStatus.current_station != startAgvLoc)
                        //{ 
                        //    rbs= BasicInfo.AgvService.addTask("SELF_POSITION", endAgvLoc);
                        //}
                        //else
                        //{
                            rbs = BasicInfo.AgvService.addTask(startAgvLoc, endAgvLoc);
                        //}
                        if (rbs.ret_code == 0)
                        {
                            AddListBak_Agv("AGV任务下发:(" + startAgvLoc + ")-(" + endAgvLoc + ")成功");
                        }
                        else
                        {
                            AddListBak_Agv("AGV任务下发失败," + startAgvLoc + "-" + endAgvLoc + ", 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                            
                        }
                    }
                }
            }
            else
            {
                AddListBak_Agv("请输入指令到达位置");
            }
        }

        private void btnSendTaskReportInit_Click(object sender, EventArgs e)
        {
            AGVController.AgvModel.robot_base_res rbs=BasicInfo.AgvService.ConfigPush(); 
            if (rbs.ret_code == 0)
            {
                AddListBak("AGV推送上报任务下发成功!");
            }
            else
            {
                AddListBak("AGV推送上报任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
            }
        }

        private void btnSendPositionReportInit_Click(object sender, EventArgs e)
        {
        }

        private void btnSendBatteryReportInit_Click(object sender, EventArgs e)
        {

        }

        private void btnSendAlarmReportInit_Click(object sender, EventArgs e)
        {
        }

        private void btnTaskCancle_Click(object sender, EventArgs e)
        {
            AGVController.AgvModel.robot_base_res rbs = BasicInfo.AgvService.cancelTask();
            if (rbs.ret_code == 0)
            {
                AddListBak("AGV取消任务下发成功!");
            }
            else
            {
                AddListBak("AGV取消任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
            }
        }

        private void btnTaskPause_Click(object sender, EventArgs e)
        {
            AGVController.AgvModel.robot_base_res rbs= BasicInfo.AgvService.pauseTask();
            if (rbs.ret_code == 0)
            {
                AddListBak("AGV暂停任务下发成功!");
            }
            else
            {
                AddListBak("AGV暂停任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
            }
        }

        private void btnTaskRestore_Click(object sender, EventArgs e)
        {
            AGVController.AgvModel.robot_base_res rbs = BasicInfo.AgvService.resumeTask();
            if (rbs.ret_code == 0)
            {
                AddListBak("AGV继续任务下发成功!");
            }
            else
            {
                AddListBak("AGV继续任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
            }
        }
        private void btnGetFinishToWcs_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x04);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void btnSetFinishToWcs_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x07);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void btnTaskFinishToWcs_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x08);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {
                GetWcsLocNo();
            }
            else if (tabControl1.SelectedIndex == 4)
            {
                SearchPos();
            }
        }

        private void GetWcsLocNo()
        {
            cmbStartWcsLocNo.Items.Clear();
            cmbEndWcsLocNo.Items.Clear();
            string sql = " SELECT * FROM WCS_AGV_LOC order by AGV_LOC ";
            DataSet dsAgvLocEnd = DbHelperSQLite.Query(sql);
            if (dsAgvLocEnd != null)
                if (dsAgvLocEnd.Tables.Count > 0)
                    if (dsAgvLocEnd.Tables[0].Rows.Count > 0)
                    {
                        for(int i=0;i< dsAgvLocEnd.Tables[0].Rows.Count;i++)
                        {
                            cmbStartWcsLocNo.Items.Add(dsAgvLocEnd.Tables[0].Rows[i]["WCS_LOC"].ToString());
                            cmbEndWcsLocNo.Items.Add(dsAgvLocEnd.Tables[0].Rows[i]["WCS_LOC"].ToString());
                        }
                    }
        }
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl2.SelectedIndex == 1)
            {
                bool blSearch = false;

                DataSet ds = GetAgvTasks("");
                if (ds != null)
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            blSearch = true;
                            ds.Tables[0].Columns.Add("DEL");
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                ds.Tables[0].Rows[i]["DEL"] = "删除";
                            }
                        }
                if (blSearch)
                {
                    dgvTaskInfoSearch.AutoGenerateColumns = false;
                    dgvTaskInfoSearch.DataSource = ds.Tables[0];
                }
                else dgvTaskInfoSearch.DataSource = null;
            }
        }

        private void btnTaskStatus_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 0;
        }

        private void btnAgvControl_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 1;
        }

        private void btnForkControl_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 2;
        }

        private void btnLog_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 0;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("您真的要退出本系统吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                allThreadValue = 1;

                Thread.Sleep(2000);
                System.Diagnostics.Process tt = System.Diagnostics.Process.GetProcessById(System.Diagnostics.Process.GetCurrentProcess().Id);
                tt.Kill();
            }
        }

        private int SendAutoChargeFlag = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            lbCurrentDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            lbCurrentTime.Text = DateTime.Now.ToString("HH:mm:ss");

            try
            {
                string strDT1 = iniFile.IniReadValue("SysInfo", "AgvAutoChangeDT1");
                //第一个时间点自动充
                DateTime dt1 = Convert.ToDateTime(strDT1);
                DateTime dtNow = DateTime.Now;
                double iMinutes = dtNow.Subtract(dt1).TotalMinutes;
                if (iMinutes >= -1 && iMinutes < 0)
                {
                    SendAutoChargeFlag = 0;
                }
                if (iMinutes >= 0 && iMinutes < 1)
                {
                    if (SendAutoChargeFlag == 0)
                    {
                        //开启自动充电
                        if (CTaskInfo.CurrentTask == null)
                        {
                            string strAgvStatusTmp = "";
                            string strAgvTaskNoTmp = "";
                            lbTaskStatus.BeginInvoke(new EventHandler(delegate
                            {
                                strAgvStatusTmp = lbTaskStatus.Text;
                            }));
                            lbTaskNo.BeginInvoke(new EventHandler(delegate
                            {
                                strAgvTaskNoTmp = lbTaskNo.Text;
                            }));
                            if (strAgvStatusTmp == "空闲" || strAgvStatusTmp == "")
                            {
                                CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                                if (CTaskInfo.AgvCurrentLoc == CTaskInfo.AgvGetSetPointLoc)
                                {
                                    cTaskStatus.AgvAutoChange = 0;
                                    cTaskStatus.AgvAutoChange = 1;
                                    AddListBak(strDT1 + "定时1开始自动充电");

                                    SendAutoChargeFlag = 1;
                                }
                                else
                                {
                                    AddListBak(strDT1 + "定时1自动充电时不在取货口位置,当前位置" + CTaskInfo.AgvCurrentLoc + ",取货口位置" + CTaskInfo.AgvGetSetPointLoc);
                                }
                            }
                            else
                            {
                                AddListBak(strDT1 + "定时1自动充电时AGV非空闲" + strAgvStatusTmp);
                            }
                        }
                        else
                        {
                            AddListBak(strDT1 + "定时1自动充电时有任务");
                        }
                    }
                }
            }
            catch (Exception exc)
            {

            }
            try
            {
                string strDT2 = iniFile.IniReadValue("SysInfo", "AgvAutoChangeDT2");
                //第一个时间点自动充
                DateTime dt2 = Convert.ToDateTime(strDT2);
                DateTime dtNow = DateTime.Now;
                double iMinutes = dtNow.Subtract(dt2).TotalMinutes;
                if (iMinutes >= -1 && iMinutes < 0)
                {
                    SendAutoChargeFlag = 0;
                }
                if (iMinutes >= 0 && iMinutes < 1)
                {
                    if (SendAutoChargeFlag == 0)
                    {
                        //开启自动充电
                        if (CTaskInfo.CurrentTask == null)
                        {
                            string strAgvStatusTmp = "";
                            string strAgvTaskNoTmp = "";
                            lbTaskStatus.BeginInvoke(new EventHandler(delegate
                            {
                                strAgvStatusTmp = lbTaskStatus.Text;
                            }));
                            lbTaskNo.BeginInvoke(new EventHandler(delegate
                            {
                                strAgvTaskNoTmp = lbTaskNo.Text;
                            }));
                            if (strAgvStatusTmp == "空闲" || strAgvStatusTmp == "")
                            {
                                CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
                                if (CTaskInfo.AgvCurrentLoc == CTaskInfo.AgvGetSetPointLoc)
                                {
                                    cTaskStatus.AgvAutoChange = 0;
                                    cTaskStatus.AgvAutoChange = 1;
                                    AddListBak(strDT2 + "定时2开始自动充电");

                                    SendAutoChargeFlag = 1;
                                }
                                else
                                {
                                    AddListBak(strDT2 + "定时2自动充电时不在取货口位置,当前位置" + CTaskInfo.AgvCurrentLoc + ",取货口位置" + CTaskInfo.AgvGetSetPointLoc);
                                }
                            }
                            else
                            {
                                AddListBak(strDT2 + "定时2自动充电时AGV非空闲="+strAgvStatusTmp);
                            }
                        }
                        else
                        {
                            AddListBak(strDT2 + "定时2自动充电时有任务");
                        }
                    }
                }
            }
            catch (Exception exc)
            {

            }

            #region 早上6点自动充电的功能取消 修改为上面参数控制的

            //if (DateTime.Now.Hour == 5)
            //    SendAutoChargeFlag = 0;
            //if(DateTime.Now.Hour==6)
            //{
            //    if (SendAutoChargeFlag == 0)
            //    {
            //        //开启自动充电
            //        if (CTaskInfo.CurrentTask == null)
            //        {
            //            string strAgvStatusTmp = "";
            //            string strAgvTaskNoTmp = "";
            //            lbTaskStatus.BeginInvoke(new EventHandler(delegate
            //            {
            //                strAgvStatusTmp = lbTaskStatus.Text;
            //            }));
            //            lbTaskNo.BeginInvoke(new EventHandler(delegate
            //            {
            //                strAgvTaskNoTmp = lbTaskNo.Text;
            //            }));
            //            if (strAgvStatusTmp == "空闲" && string.IsNullOrEmpty(strAgvTaskNoTmp))
            //            {
            //                CTaskInfo.AgvCurrentLoc = iniFile.IniReadValue("SysInfo", "AGV_CurrentLocNo");
            //                if (CTaskInfo.AgvCurrentLoc == CTaskInfo.AgvGetSetPointLoc)
            //                {
            //                    cTaskStatus.AgvAutoChange = 1;
            //                    AddListBak("定时开始自动充电");

            //                    SendAutoChargeFlag = 1;
            //                }
            //                else
            //                {
            //                    AddListBak("自动充电时不在取货口位置,当前位置" + CTaskInfo.AgvCurrentLoc + ",取货口位置" + CTaskInfo.AgvGetSetPointLoc);
            //                }
            //            }
            //            else
            //            {
            //                AddListBak("自动充电时AGV非空闲");
            //            }
            //        }
            //        else
            //        {
            //            AddListBak("自动充电时有任务");
            //        }
            //    }
            //}
            #endregion
        }

        private void button3_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x00);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x01);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x02);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x03);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button4_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x05);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void button5_Click(object sender, EventArgs e)
        {

            CTaskInfo.AddToWcsSendDataList(0x02, 0x01, 0x06);
            Button btnThis = (Button)sender;
            AddListBak(btnThis.Text);
            lbForkTip.Text = btnThis.Text;
        }

        private void btnTaskStatus_MouseEnter(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatStyle = FlatStyle.Flat;
        }

        private void btnTaskStatus_MouseLeave(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatStyle = FlatStyle.Popup;
        }

        private void btnSendAlarmReportInit_MouseEnter(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatAppearance.BorderColor = Color.Yellow;
        }

        private void btnSendAlarmReportInit_MouseLeave(object sender, EventArgs e)
        {
            Button btnThis = (Button)(sender);
            btnThis.FlatAppearance.BorderColor = Color.FromArgb(0, 0, 192); ;
        }

        private void lbTaskNo_MouseClick(object sender, MouseEventArgs e)
        {
            if (lbTaskNo.Text == "") return;
            contextMenuStrip2.Show(MousePosition.X, MousePosition.Y + 12);
        }

        private void tsmiTaskDelete_Click(object sender, EventArgs e)
        {
            //if (System.Windows.Forms.MessageBox.Show("确定要删除任务" + lbTaskNo.Text + "?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
            //    return;
            //bllTaskAgv.Delete(CTaskInfo.CurrentTask.TASK_ID);
            //CTaskInfo.IsHasTask = false;
        }

        private void btnSendToFork_Click(object sender, EventArgs e)
        {
            string strLoc = tbHandSendLocNo.Text.Trim();
            if (strLoc.Length < 6)
            {
                MessageBox.Show("储位不正确!");
                return;
            }
            if (radioButtonMove.Checked)
            {
                short shRow = short.Parse(strLoc.Substring(0, 2));
                short shCell = short.Parse(strLoc.Substring(2, 2));
                short shFloor = short.Parse(strLoc.Substring(4, 2));
                AGVForkSendCode(shRow, shCell, shFloor, 1);

                AddListBak("手动下发货叉移动任务,货位:" + strLoc);
                lbForkTip.Text = "手动下发货叉移动任务,货位:" + strLoc;

            }
            else if (radioButtonGet.Checked)
            {
                short shRow = short.Parse(strLoc.Substring(0, 2));
                short shCell = short.Parse(strLoc.Substring(2, 2));
                short shFloor = short.Parse(strLoc.Substring(4, 2));
                AGVForkSendCode(shRow, shCell, shFloor, 2);
                AddListBak("手动下发货叉取货任务,货位:" + strLoc);
                lbForkTip.Text = "手动下发货叉取货任务,货位:" + strLoc;
            }
            else if (radioButtonSet.Checked)
            {
                short shRow = short.Parse(strLoc.Substring(0, 2));
                short shCell = short.Parse(strLoc.Substring(2, 2));
                short shFloor = short.Parse(strLoc.Substring(4, 2));
                AGVForkSendCode(shRow, shCell, shFloor, 3);
                AddListBak("手动下发货叉放货任务,货位:" + strLoc);
                lbForkTip.Text = "手动下发货叉放货任务,货位:" + strLoc;
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
        }

        private void btnReset_MouseDown(object sender, MouseEventArgs e)
        {

            AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉复位=1");
            lbForkTip.Text = "手动下发货叉复位=1";
        }

        private void btnReset_MouseUp(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);
            AddListBak("手动下发货叉复位=0");
            lbForkTip.Text = "手动下发货叉复位=0";
        }

        private void btnTaskClear_Click(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉任务清除");
            lbForkTip.Text = "手动下发货叉任务清除";
        }

        private void btnTaskContinue_Click(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_Task_Continue_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉任务继续");
            lbForkTip.Text = "手动下发货叉任务继续";
        }

        private void btnEmergencyStop_Click(object sender, EventArgs e)
        {
            if (btnEmergencyStop.Text == "急停按下")
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_EmergencyStop_ToPlc_Addr, 1, 1, 1, 1);
                AddListBak("手动下发货叉急停按下");
                btnEmergencyStop.Text = "急停旋开";
                lbForkTip.Text = "手动下发货叉急停按下";
            }
            else
            {
                AddToPLCSRMDataList(cTaskStatus.SRM_EmergencyStop_ToPlc_Addr, 1, 0, 1, 1);
                AddListBak("手动下发货叉急停旋开");
                btnEmergencyStop.Text = "急停按下";
                lbForkTip.Text = "手动下发货叉急停旋开";
            }
        }

        private void btnSendRemoteAuto_Click(object sender, EventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_HandAuto_ToPlc_Addr, 1, 0, 1, 1);

            AddToPLCSRMDataList(cTaskStatus.SRM_RemoteAuto_ToPlc_Addr, 1, 1, 1, 1);
            AddListBak("手动下发货叉远程自动模式");
            lbForkTip.Text = "手动下发货叉远程自动模式";
            leftbutton.Enabled = false;
            rightbutton.Enabled = false;
            btnForkUpMove.Enabled = false;
            btnForkDownMove.Enabled = false;
        }

        private void btnTaskLog_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 1;
        }

        private void btnAgvRunLog_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 2;
        }

        private void btnForkRunLog_Click(object sender, EventArgs e)
        {
            tabControl1.SelectedIndex = 3;
            tabControl2.SelectedIndex = 3;
        }

        private void 待下发ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 待下发 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 0);
            lbTaskStatus.Text = GetTaskStatusTxt(0);
        }

        private void 待执行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 待执行 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
           
            BasicInfo.AgvService.cancelTask();//取消AGV任务 

            AddToPLCSRMDataList(cTaskStatus.SRM_Task_Clear_ToPlc_Addr, 1, 1, 1, 1);// 取消货叉任务
            //复位
            AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 1, 1, 1);
            
            Thread.Sleep(500);
            AddToPLCSRMDataList(cTaskStatus.SRM_ReSet_ToPlc_Addr, 1, 0, 1, 1);

            UpdateTaskStatus(lbTaskNo.Text, 1);
            lbTaskStatus.Text = GetTaskStatusTxt(1);
        }

        private void 取货行走中ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 取货行走中 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 2);
            lbTaskStatus.Text = GetTaskStatusTxt(2);
        }

        private void 到达取货位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 到达取货位 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 3);
            lbTaskStatus.Text = GetTaskStatusTxt(3);
        }

        private void 取货完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 取货完成 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 5);
            lbTaskStatus.Text = GetTaskStatusTxt(5);
            CTaskInfo.CurrentTask.forkHStatus = "0";
        }

        private void 放货行走中ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 放货行走中 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 6);
            lbTaskStatus.Text = GetTaskStatusTxt(6);
        }

        private void 到达放货位ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 到达放货位 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 7);
            lbtask_status.Text = GetTaskStatusTxt(7);
        }

        private void 放货完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 放货完成 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 8);
            lbtask_status.Text = GetTaskStatusTxt(8);
        }

        private void 任务完成ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要把任务" + lbTaskNo.Text + "设置为 任务完成 状态?", "设置确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;
            UpdateTaskStatus(lbTaskNo.Text, 14);
            lbtask_status.Text = GetTaskStatusTxt(14);

            CTaskInfo.CurrentTask = null;
            CTaskInfo.PLCSRMTaskSendList.Clear();
            CTaskInfo.AGVTaskSendList.Clear();
            FlushPage();
        }

        private void 任务删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (System.Windows.Forms.MessageBox.Show("确定要删除任务" + lbTaskNo.Text + "?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                return;

            DeleteTask(lbTaskNo.Text);
            CTaskInfo.CurrentTask = null;
            CTaskInfo.PLCSRMTaskSendList.Clear();
            CTaskInfo.AGVTaskSendList.Clear();
            FlushPage();
        }

        private void btnReadPlc_Click(object sender, EventArgs e)
        {
            if (checkBoxReadBool.Checked)
            {
                PLCMsgModel plcMM = plcSRM1.PLCReadBool(tbReadPlcAddr.Text.Trim());
                if (plcMM.Code == 1)
                {
                    bool bRead = (bool)plcMM.Val;
                    tbReadResult.Text = bRead ? "true" : "false";
                }
                else
                {
                    tbReadResult.Text = plcMM.Msg;
                }
            }
            else
            {
                PLCMsgModel plcMM = plcSRM1.PLCReadByte(tbReadPlcAddr.Text.Trim());
                if (plcMM.Code == 1)
                {
                    short bRead = (short)plcMM.Val;
                    tbReadResult.Text = bRead.ToString();
                }
                else
                {
                    tbReadResult.Text = plcMM.Msg;
                }
            }
        }

        private void btnWritePlc_Click(object sender, EventArgs e)
        {
            if (checkBoxWriteBool.Checked)
            {
                PLCMsgModel plcMM = plcSRM1.PLCWrite(tbWritePLcAddr.Text.Trim(), bool.Parse(tbWritePLcValue.Text.Trim()));
                if (plcMM.Code == 1)
                {
                    tbWritePLcValue.Text = "写入成功";
                }
                else
                {
                    tbWritePLcValue.Text = plcMM.Msg;
                }
                tbWritePLcValue.Focus();
                tbWritePLcValue.Select();
                tbWritePLcValue.SelectAll();
            }
            else
            {
                PLCMsgModel plcMM = plcSRM1.PLCWrite(tbWritePLcAddr.Text.Trim(), short.Parse(tbWritePLcValue.Text.Trim()));
                if (plcMM.Code == 1)
                {
                    tbWritePLcValue.Text = "写入成功";
                }
                else
                {
                    tbWritePLcValue.Text = plcMM.Msg;
                }
                tbWritePLcValue.Focus();
                tbWritePLcValue.Select();
                tbWritePLcValue.SelectAll();
            }


        }

        private void btnSendChargingTask_Click(object sender, EventArgs e)
        {
            AGVController.AgvModel.robot_base_res rbs = new AGVController.AgvModel.robot_base_res();
            rbs = BasicInfo.AgvService.addTask("SELF_POSITION", CTaskInfo.AgvChargingLoc);
            if (rbs.ret_code == 0)
            {
                AddListBak_Agv("AGV任务下发:(SELF_POSITION)-(" + CTaskInfo.AgvChargingLoc + ")成功");
            }
            else
            {
                AddListBak("AGV任务下发失败,SELF_POSITION-" + CTaskInfo.AgvChargingLoc + ", 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
            }
        }

        private void btnSendToInitLocTask_Click(object sender, EventArgs e)
        {
        }

        private void btnSendCode_Click(object sender, EventArgs e)
        {
        }

        private void btnTurnleft90_Click(object sender, EventArgs e)
        {
        }

        private void btnTurnRight90_Click(object sender, EventArgs e)
        {
        }

        private void btnTurnBack_Click(object sender, EventArgs e)
        {

        }

        private void btnSendInTask_Click(object sender, EventArgs e)
        {
            AGVController.AgvModel.robot_base_res rbs = BasicInfo.AgvService.robot_control_comfirmloc_req();
            if (rbs.ret_code == 0)
            {
                AddListBak("AGV定位确认下发成功!");
            }
            else
            {
                AddListBak("AGV定位确认下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
        }

        private void btnSendOutTask_Click(object sender, EventArgs e)
        {
        }

        private void btnToZeroPoint_Click(object sender, EventArgs e)
        {
        }

        #region 储位坐标

        private void btnAddAllLoc_Click(object sender, EventArgs e)
        {

            try
            {
                decimal iGroup = numericUpDownRow.Value;
                int icoll = int.Parse(tbAgvLoc.Text.Trim().Substring(2, 2));
                for (int i = 1; i <= numericUpDownColl.Value; i++)
                {
                    int iSaveColl = icoll + i - 1;
                    string strAgvLoc = "LM" + iSaveColl.ToString("00");
                    for (int j = 1; j <= numericUpDownFloor.Value; j++)
                    {
                        string strWcsLoc = iGroup.ToString("00") + "-" + i.ToString("00") + "-" + j.ToString("00");


                        string sql = " SELECT COUNT(WCS_LOC) FROM WCS_AGV_LOC WHERE WCS_LOC='" + strWcsLoc + "';";
                        if (DbHelperSQLite.RecordCount(sql)==0)
                        {
                            sql = " INSERT INTO WCS_AGV_LOC (WCS_LOC,AGV_LOC,LOC_GROUP,LOC_COLL,LOC_FLOOR)" +
                                "VALUES('" + strWcsLoc + "','" + strAgvLoc + "','" + iGroup + "','" + i + "','" + j + "');";
                            DbHelperSQLite.ExecuteSql(sql);
                        }
                    }
                }

                SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void SearchPos()
        {
            dgvPos.DataSource = null; 
            string sql = " SELECT * FROM WCS_AGV_LOC ORDER BY  WCS_LOC ;";
            DataSet dsLoc = DbHelperSQLite.Query(sql);
            {
                dgvPos.AutoGenerateColumns = false;
                dgvPos.DataSource = dsLoc.Tables[0];
            }
        }

        private void btnAddOneLoc_Click(object sender, EventArgs e)
        {
            try
            {
                decimal iGroup = numericUpDownRow.Value;
                decimal iSaveColl = numericUpDownColl.Value;
                decimal iFloor = numericUpDownFloor.Value; 
                string strWcsLoc = iGroup.ToString("00") + "-" + iSaveColl.ToString("00") + "-" + iFloor.ToString("00");

                if (tbWcsLocNo.Text.Trim() != "")
                    strWcsLoc = tbWcsLocNo.Text.Trim();

                string sql = " SELECT COUNT(WCS_LOC) FROM WCS_AGV_LOC WHERE WCS_LOC='" + strWcsLoc + "';";
                if (DbHelperSQLite.RecordCount(sql)==0)
                {
                    sql = " INSERT INTO WCS_AGV_LOC (WCS_LOC,AGV_LOC,LOC_GROUP,LOC_COLL,LOC_FLOOR)" +
                        "VALUES('" + strWcsLoc + "','" + tbAgvLoc.Text.Trim() + "','" + iGroup + "','" + iSaveColl + "','" + iFloor + "');";
                    DbHelperSQLite.ExecuteSql(sql);
                }
                SearchPos();
            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnDelOneLoc_Click(object sender, EventArgs e)
        {

            try
            {
                if(dgvPos.SelectedRows.Count==0)
                {
                    MessageBox.Show("请在列表中选择要删除的储位", "提示");
                    return;
                }

                //decimal iGroup = numericUpDownRow.Value;
                //decimal iSaveColl = numericUpDownColl.Value;
                //decimal iFloor = numericUpDownFloor.Value;
                //string strWcsLoc = iGroup.ToString("00") + "-" + iSaveColl.ToString("00") + "-" + iFloor.ToString("00");

                string  strWcsLoc = dgvPos.SelectedRows[0].Cells[0].Value.ToString();
                string sql = " SELECT COUNT(WCS_LOC) FROM WCS_AGV_LOC WHERE WCS_LOC='" + strWcsLoc + "';";
                if (DbHelperSQLite.RecordCount(sql)>0)
                {
                    sql = " DELETE FROM WCS_AGV_LOC WHERE WCS_LOC='" + strWcsLoc + "';";
                    DbHelperSQLite.ExecuteSql(sql);
                }

                SearchPos();
            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowX_Click(object sender, EventArgs e)
        {
            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set x=" + tbPosX.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowY_Click(object sender, EventArgs e)
        {

            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set Y=" + tbPosY.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowZ_Click(object sender, EventArgs e)
        {

            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set Z=" + tbPosZ.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateRowW_Click(object sender, EventArgs e)
        {
            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set W=" + tbPosW.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like 'L" + numericUpDownRow.Value.ToString("00") + "%'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollX_Click(object sender, EventArgs e)
        {

            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set X=" + tbPosX.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollY_Click(object sender, EventArgs e)
        {
            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set Y=" + tbPosY.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollZ_Click(object sender, EventArgs e)
        {

            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set Z=" + tbPosZ.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnUpdateCollW_Click(object sender, EventArgs e)
        {

            try
            {
                //UYD_WCS.Model.W_POS modelPos = new UYD_WCS.Model.W_POS();
                //if (comboBoxLocType.Text != "储位")
                //{
                //    MessageBox.Show("提示", "只能更新储位坐标");
                //    return;
                //}
                //string strSql = " update w_pos set W=" + tbPosW.Text.Trim() + " where LOC_NO_TYPE='储位' and LOC_NO like '%" + numericUpDownColl.Value.ToString("00") + "'";
                //UYD_WCS.BLL.W_POS bllPos = new UYD_WCS.BLL.W_POS();
                //bllPos.ExeSql(strSql);

                //SearchPos();

            }
            catch (Exception exc)
            {
                MessageBox.Show("异常", exc.Message);
            }
        }

        private void btnLocPosSet_Click(object sender, EventArgs e)
        {

            tabControl1.SelectedIndex = 4;
            SearchPos();
        }

        #endregion

        private void btnTaskIDSetZero_Click(object sender, EventArgs e)
        {

            AddToPLCSRMDataList(cTaskStatus.SRM_TaskID_ToPlc_Addr, 1, 0, 1, 1);
            AddListBak("手动下发货叉作业号清0");
            lbForkTip.Text = "手动下发货叉作业号清0";
        }

        private void btnToFrom_Click(object sender, EventArgs e)
        {

        }

        private void btnZeroCharge_Click(object sender, EventArgs e)
        {
        }

        private void lbForkGetFinished_Click(object sender, EventArgs e)
        {
            bool blUpGetFinishStatus = false;
            if (lbForkGetFinished.BackColor == Color.Lime)
            {
                blUpGetFinishStatus = false;
            }
            else
            {
                blUpGetFinishStatus = true;
            }
            plcSRM1.PLCWrite("DB540.24.1", blUpGetFinishStatus);

        }

        private void lbForkSetFinished_Click(object sender, EventArgs e)
        {
            bool blUpSetFinishStatus = false;
            if (lbForkSetFinished.BackColor == Color.Lime)
            {
                blUpSetFinishStatus = false;
            }
            else
            {
                blUpSetFinishStatus = true;
            }
            plcSRM1.PLCWrite("DB540.24.2", blUpSetFinishStatus);
        }

        private void lbForkTaskFinished_Click(object sender, EventArgs e)
        {
            bool blUpSetFinishStatus = false;
            if (lbForkTaskFinished.BackColor == Color.Lime)
            {
                blUpSetFinishStatus = false;
            }
            else
            {
                blUpSetFinishStatus = true;
            }
            plcSRM1.PLCWrite("DB540.24.5", blUpSetFinishStatus);
        }

        private void handautobutton_Click(object sender, EventArgs e)
        {

            AddToPLCSRMDataList(cTaskStatus.SRM_HandAuto_ToPlc_Addr, 1, 1, 1, 1);

            leftbutton.Enabled = true;
            rightbutton.Enabled = true;
            btnForkUpMove.Enabled = true;
            btnForkDownMove.Enabled = true;
        }

        private void leftbutton_Click(object sender, EventArgs e)
        {

        }

        private void leftbutton_MouseDown(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_LeftMove_ToPlc_Addr, 1, 1, 1, 1);
        }

        private void leftbutton_MouseUp(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_LeftMove_ToPlc_Addr, 1, 0, 1, 1);
        }


        private void rightbutton_MouseDown(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_RightMove_ToPlc_Addr, 1, 1, 1, 1);
        }

        private void rightbutton_MouseUp(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_RightMove_ToPlc_Addr, 1, 0, 1, 1);
        }

        private void btnSendGetLastLocNo_Click(object sender, EventArgs e)
        {
        }

        private void btnForkUpMove_MouseDown(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_UpMove_ToPlc_Addr, 1, 1, 1, 1);
        }

        private void btnForkUpMove_MouseUp(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_UpMove_ToPlc_Addr, 1, 0, 1, 1);
        }

        private void btnForkDownMove_MouseDown(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_DownMove_ToPlc_Addr, 1, 1, 1, 1);
        }

        private void btnForkDownMove_MouseUp(object sender, MouseEventArgs e)
        {
            AddToPLCSRMDataList(cTaskStatus.SRM_DownMove_ToPlc_Addr, 1, 0, 1, 1);
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            if(CTaskInfo.CurrentTask!=null)
            {
                if (!string.IsNullOrEmpty(CTaskInfo.CurrentTask.taskCode))
                    if (!string.IsNullOrEmpty(CTaskInfo.CurrentTask.taskCode))
                    {
                        try
                        {
                            DateTime dtTaskDateTime = DateTime.ParseExact(CTaskInfo.CurrentTask.reqTime, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
                            if (DateTime.Now.Subtract(dtTaskDateTime).TotalMinutes > 80)
                            {

                                UpdateTaskStatus(CTaskInfo.CurrentTask.taskCode, 13);
                                CTaskInfo.CurrentTask.taskStatus = 13;
                                CTaskInfo.CurrentTask = null;
                                FlushPage();

                                AddListBak("任务单号:"+CTaskInfo.CurrentTask.taskCode+"运行超时，运行时间:"+ DateTime.Now.Subtract(dtTaskDateTime).TotalMinutes+"分钟,系统强制完成!");

                            }
                        }
                        catch
                        {

                        }
                    }
            }
            if (DateTime.Now.Hour == 0)
            {
                string strFolderPath = Application.StartupPath + "\\Log";

                if (Directory.Exists(strFolderPath))
                {
                    DirectoryInfo di = new DirectoryInfo(strFolderPath);
                    var fiArr = di.GetFileSystemInfos();
                    foreach (var f in fiArr)
                    {
                        if (f is DirectoryInfo)
                        {
                            DirectoryInfo thisDir = (DirectoryInfo)f;
                            foreach (FileInfo fiInfo in thisDir.GetFiles())
                            {
                                if (DateTime.Now.Subtract(fiInfo.CreationTime).Days > 30)
                                {
                                    fiInfo.Delete();
                                }

                            }
                        }
                    }
                }


                string strFolderPathWcs = Application.StartupPath + "\\AGV_WCS_Logs";

                if (Directory.Exists(strFolderPathWcs))
                {
                    DirectoryInfo di = new DirectoryInfo(strFolderPathWcs);
                    var fiArr = di.GetFileSystemInfos();
                    foreach (var f in fiArr)
                    {
                        if (f is DirectoryInfo)
                        {
                            DirectoryInfo thisDir = (DirectoryInfo)f;
                            foreach (FileInfo fiInfo in thisDir.GetFiles())
                            {
                                if (DateTime.Now.Subtract(fiInfo.CreationTime).Days > 30)
                                {
                                    fiInfo.Delete();
                                }

                            }
                        }
                    }
                }


                AddListBak("自动执行删除一个月前的日志文件");


                string sql= " DELETE FROM WCS_AGV_TASK WHERE reqTime <'" + DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss") + "' ";
                DbHelperSQLite.ExecuteSql(sql);

                AddListBak("自动执行删除一个月前的任务信息");
            }
        }

        private void btnAgvEstop_Click(object sender, EventArgs e)
        {
            AgvPauseOrReset(true);
        }

        private void btnAgvReset_Click(object sender, EventArgs e)
        {
            AgvPauseOrReset(false);
        }

        /// <summary>
        /// 暂停=true；复位=false;
        /// </summary>
        private void AgvPauseOrReset( bool flag )
        {
            AGVController.AgvModel.robot_base_res rbs = new AGVController.AgvModel.robot_base_res();           
            if (flag)
            {
                //AGV急停
                AddListBak("AGV下发任务暂停指令");
                rbs=BasicInfo.AgvService.pauseTask();
                if (rbs.ret_code == 0)
                {
                    AddListBak("AGV暂停任务下发成功!");
                }
                else
                {
                    AddListBak("AGV暂停任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                }
            }
            else
            {
                //AGV解除急停
                AddListBak("AGV下发任务继续指令");
                rbs = BasicInfo.AgvService.resumeTask();
                if (rbs.ret_code == 0)
                {
                    AddListBak("AGV继续任务下发成功!");
                }
                else
                {
                    AddListBak("AGV继续任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                }
            }
        }

        private void AgvSoftEMC(bool flag)
        {
            AGVController.AgvModel.robot_base_res rbs = new AGVController.AgvModel.robot_base_res();
            if (flag)
            {
                //AGV急停
                AddListBak("AGV下发软急停指令");
                rbs = BasicInfo.AgvService.robot_other_softemc_req(true);
                if (rbs.ret_code == 0)
                {
                    AddListBak("AGV软急停任务下发成功!");
                }
                else
                {
                    AddListBak("AGV软急停任务下发失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                }
            }
            else
            {
                //AGV解除急停
                AddListBak("AGV下发软急停复位指令");
                rbs = BasicInfo.AgvService.robot_other_softemc_req(false);
                if (rbs.ret_code == 0)
                {
                    AddListBak("AGV下发软急停复位指令下发成功!");
                }
                else
                {
                    AddListBak("AGV下发软急停复位指令失败, 错误码:" + rbs.ret_code + "=" + rbs.err_msg);
                }
            }
        }

        private void label38_Click(object sender, EventArgs e)
        {
            cTaskStatus.SRM_BreakDownInfo = 0;
        }

        private void label39_Click(object sender, EventArgs e)
        {
            cTaskStatus.SRM_BreakDownInfo = 14;
        }

        private void dgvTaskInfoSearch_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            if(e.ColumnIndex==8)
            {
                string strTaskNo = dgvTaskInfoSearch.Rows[e.RowIndex].Cells[0].Value.ToString();
                if (System.Windows.Forms.MessageBox.Show("确定要删除任务" + strTaskNo + "?", "删除确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                DeleteTask(strTaskNo);

                bool blSearch = false;
                DataSet ds = GetAgvTasks("");
                if (ds != null)
                    if (ds.Tables.Count > 0)
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            blSearch = true;
                            ds.Tables[0].Columns.Add("DEL");
                            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                            {
                                ds.Tables[0].Rows[i]["DEL"] = "删除";
                            }
                        }
                if (blSearch)
                {
                    dgvTaskInfoSearch.AutoGenerateColumns = false;
                    dgvTaskInfoSearch.DataSource = ds.Tables[0];
                }
                else dgvTaskInfoSearch.DataSource = null;
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            string TaskFinishV = tbTaskFinish.Text.Trim();
            int TaskFinishR = 0;
            if (TaskFinishV == "")
            {
                MessageBox.Show("状态不能为空");
                return;
            }
            if (TaskFinishV=="0")
            {
                TaskFinishR = 0;
            }
            else
            if (TaskFinishV == "1")
            {
                TaskFinishR = 1;
            }
           else
            {
                MessageBox.Show("状态只能为1或0");
                return;
            }
            cTaskStatus.SRM_Task_Finish = TaskFinishR;
        }

        private void button7_Click(object sender, EventArgs e)
        {
            string TaskFinishV = tbTaskFinish.Text.Trim();
            int TaskFinishR = 0;
            if (TaskFinishV == "")
            {
                MessageBox.Show("状态不能为空");
                return;
            }
            if (TaskFinishV == "0")
            {
                TaskFinishR = 0;
            }
            else
            if (TaskFinishV == "1")
            {
                TaskFinishR = 1;
            }
            else
            {
                MessageBox.Show("状态只能为1或0");
                return;
            }
            cTaskStatus.SRM_Get_Finish = TaskFinishR;
        }

        private void button9_Click(object sender, EventArgs e)
        {
            string TaskFinishV = tbTaskFinish.Text.Trim();
            int TaskFinishR = 0;
            if (TaskFinishV == "")
            {
                MessageBox.Show("状态不能为空");
                return;
            }
            if (TaskFinishV == "0")
            {
                TaskFinishR = 0;
            }
            else
            if (TaskFinishV == "1")
            {
                TaskFinishR = 1;
            }
            else
            {
                MessageBox.Show("状态只能为1或0");
                return;
            }
            cTaskStatus.SRM_Set_Finish = TaskFinishR;
        }
    }
}
